Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue with Haskell's "do"

I wrote a Haskell function that calculates the factorial of every number in a given list and prints it to the screen.

factPrint list =
if null list
    then putStrLn ""
    else do putStrLn ((show.fact.head) list)
        factPrint (tail list)

The function works, but I find the third line a bit confusing. Why hasn't the compiler(GHC) reported an error on it since there is no "do" before the "putStrLn" (quasi?)function? If I omit "do" from the 4th line, an error pops up as expected.

I'm quite new to Haskell and its ways, so please pardon me if I said something overly silly.

like image 473
vuzun Avatar asked Nov 29 '22 20:11

vuzun


1 Answers

do putStrLn ((show.fact.head) list)
   factPrint (tail list)

is actually another way of writing

putStrLn ((show.fact.head) list) >> factPrint (tail list)

which, in turn, means

putStrLn ((show.fact.head) list) >>= \_ -> factPrint (tail list)

The do notation is a convenient way of stringing these monads together, without this other ugly syntax.

If you only have one statement inside the do, then you are not stringing anything together, and the do is redundant.

like image 53
newacct Avatar answered Dec 05 '22 03:12

newacct