0

I am new to Haskell so this question should be fairly trivial to most Haskell programmers: I've got a function digits :: Integer -> [Int] which converts an integer to a list of its digits (123 to [1,2,3]). To now get the sum of those digits I enter sum $ digits 123 in ghci and everything works, it outputs 6. As soon as I create the function in a file as follows, however, I get an error. It probably has to do with the fact that ghci infers a type for 123, but that is not enough so I can fix the problem.

The function in a text file:

digitalSum :: Integer -> Int
digitalSum = sum $ digits

and the error:

* Couldn't match type `[Int]' with `Integer -> Int'
  Expected type: Integer -> Integer -> Int
    Actual type: Integer -> [Int]
* In the second argument of `($)', namely `digits'
  In the expression: sum $ digits
  In an equation for `digitalSum': digitalSum = sum $ digits
Taxel
  • 3,859
  • 1
  • 18
  • 40
  • 1
    See also: [*Haskell: difference between . (dot) and $ (dollar sign)*](http://stackoverflow.com/q/940382/2751851) – duplode Jan 16 '17 at 14:45

2 Answers2

5

While sum $ digits 123 works in GHCi (just as it will in a Haskell file), sum $ digits (which could just as well be written sum digits) won't work in GHCi either.

The problem is that sum takes a list of numbers, but digits is not a list, it's a function.

You want either digitalSum x = sum $ digits x or digitalSum = sum . digits. Here . is the function composition operator, which creates a function out of two existing functions (as opposed to $, which takes a function and its argument, not another function).

sepp2k
  • 363,768
  • 54
  • 674
  • 675
3

You forgot the argument

digitalSum :: Integer -> Int
digitalSum x = sum $ digits x

Alternatively, you can use function composition

digitalSum :: Integer -> Int
digitalSum = sum . digits
chi
  • 111,837
  • 3
  • 133
  • 218