2
votes

Basically, what I want to do is receive a number, split into a list of its digits and then double each value.

However, I don't want to use Integer type, because I might use some other functions containing type variable. I was trying to do something like that:

digs :: (Integral a) => a -> [a] 
digs 0 = []
digs x = digs (x `div` 10) ++ [x `mod` 10]

double :: (Integral a) => [a] -> [a]
double xs = [x*2 | x <- xs]

Both functions works alone, but if I try something like "double digs 1234" it gives me an error.

Couldn't match expected type 'Integer -> t' with actual type '[Integer]'

I'm not sure what this msg means.

1
you need to use function composition, double . digs $ 1234 - Chase
Thanks. It worked. Could you explain me the reason please? - frederico s
Or double $ digs 1234. Or even just using parentheses: double (digs 1234) - Robin Zigmond

1 Answers

2
votes

As said in the comments, you need to compose your functions. Haskell interprets double digs 1234 as (double digs) 1234. So haskell thinks you are passing in the function digs as an argument to double. Here's the full error message I get from your example:

<interactive>:3:1: error:
    • Couldn't match expected type ‘Integer -> t’
                  with actual type ‘[Integer]’
    • The function ‘double’ is applied to two arguments,
      but its type ‘[Integer] -> [Integer]’ has only one
      In the expression: double digs 1234
      In an equation for ‘it’: it = double digs 1234
    • Relevant bindings include it :: t (bound at <interactive>:3:1)

<interactive>:3:8: error:
    • Couldn't match expected type ‘[Integer]’
                  with actual type ‘Integer -> [Integer]’
    • Probable cause: ‘digs’ is applied to too few arguments
      In the first argument of ‘double’, namely ‘digs’
      In the expression: double digs 1234
      In an equation for ‘it’: it = double digs 1234

Note in the first error message: "The function double is applied to two arguments, but its type only has one." Haskell reads this as passing digs first to double, and then passing 1234.

So you need to make sure 1234 is passed to digs first, then pass that result to double. I think the most beginner friendly way is with parens:

*Main> double (digs 1234)
[2,4,6,8]

Haskell's function calling style is pretty different from most languages, so it takes some time to get used to.