1

I have this function to create a list of lists, according to some rules i implemented, but it gives me an annoying error, i can't understand how to fix.

Here's the list it receives:

["3123","11254","790","86214","114125","36214"]

and the value is

num = 7

Here's the function:

create_list_of_lists :: Integral t => [t] -> t -> [t]
create_list_of_lists (x:xs) num = [x `div`z | x <- xs, z <- [1..num]]

When i compile it, i get no errors, but when i run it with this command:

create_list_of_lists ["3123","11254","790","86214","114125","36214"] 7

i get this errors:

run_function

What am i doing wrong ?

1
  • The error message tells you exactly what's wrong: No instance for Integral [Char]; No instance for Num [Char]. The type [Char] does not have an instance for Integral or Num, which tells you that you're probably passing in the wrong type. These error can also sometimes mean that you have the wrong constraints on your function, such as if you have Integral and Fractional (these are obviously not compatible mathematically), but these issues are more rare. Commented Nov 17, 2014 at 14:40

2 Answers 2

3

That's because you are passing it as list of String and not as list of Integer. This should work:

*Main> create_list_of_lists [3123,11254,790,86214,114125,36214] 7
[11254,5627,3751,2813,2250,1875,1607,790,395,263,197,158,131,112,86214,43107,28738,21553,17242,14369,12316,114125,57062,38041,28531,22825,19020,16303,36214,18107,12071,9053,7242,6035,5173]

If you want to pass it as a list of strings then perform the conversion using the read function. Something like this:

*Main> let y =  ["3123","11254","790","86214","114125","36214"] 
*Main> let x = map read y :: [Int]
*Main> x
[3123,11254,790,86214,114125,36214]

Or as @bheklir says you can use readMaybe which will convert them safely.

Sign up to request clarification or add additional context in comments.

4 Comments

However, if i must pass a list of Strings, how can i do it ?
@dcarou You should convert your list of Strings into a list of Int, you can do this unsafely with read, but I always recommend Text.Read.readMaybe which can fail safely, then you can use Data.Maybe.catMaybes to get a list of all the successful conversions to Int.
@dcarou Can you create a new question for that ?
0

You are passing around as a string . Please use

create_list_of_lists [3123,11254,790,86214,114125,36214] 7

Additionally you can use read for your intended purpose

let create_list_of_lists (x:xs) num = [read x `div`z | x <- xs, z <- [1..num]]

http://hackage.haskell.org/package/base-4.7.0.1/docs/Text-Read.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.