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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With