Bernardo Meurer
Bernardo Meurer

Reputation: 2335

Haskell print factorial

I've just started programming Haskell, basically because I was looking for a more mathematically powerful language then C#, and right now I'm very confused.

Right now I'm trying to simply find the the factorial of 4 and print that, this is what I wrote so far:

fact n = product [1..n]
main = do
   print fact 4

When I try to debug it i get

Error:(3, 8) ghc: Couldn't match expected type a1 -> t0' with actual typeIO ()' The function print' is applied to two arguments, but its type(a0 -> a0) -> IO ()' has only one In a stmt of a 'do' block: print fact 4 In the expression: do { print fact 4 }

What am I doing wrong?

Upvotes: 0

Views: 699

Answers (1)

bheklilr
bheklilr

Reputation: 54058

You need parentheses:

main = do
    print (fact 4)

What GHC is seeing is fact and 4 being passed as separate arguments to print, but what you want is to apply 4 to fact, then apply that result to print. You could also use

main = do
    print $ fact 4

The $ operator doesn't do anything in itself, but it has a very low precedence, like how + is lower precedence than *, and it associates to the right, so you can write something like

f $ g . h $ m 1 $ 2 + 3

Instead of

f ((g . h) (m 1 (2 + 3)))

Upvotes: 9

Related Questions