I want to print the following output.
import Data.Char
main = do
output = map toUpper "helloworld"
putStrLn output
It failed with the error message.
test.hs:4:12: error:
parse error on input ‘=’
Suggested fix:
Perhaps you need a 'let' in a 'do' block?
e.g. 'let x = 5' instead of 'x = 5'
|
4 | output = map toUpper "helloworld"
|
However, if I use let binding, it works. Why?
main = do
-- it works
let output = map toUpper "helloworld"
putStrLn output
CodePudding user response:
Inside do
, the syntax does require one to use let variable = expression
, as the error message suggests. There's not much to say about that syntactical choice.
One might wonder why variable = expression
(without let
) was not chosen as the correct syntax. It's hard to guess the rationale, but note that
foo = do
let x1 = e1
let x2 = e2
...
and
foo = do
let x1 = e1
x2 = e2
...
are both valid. The main difference is that the latter allows both e1
and e2
to refer to both x1
and x2
, which is useful for mutually recursive definitions. By contrast, in the former do
block e1
can not refer to x2
.
The point is that after a let
one can write a block of defining equations, and not just a single one.
Anyway, the difference explained above is not that important in practice since we do not use mutual recursion that often. Still, it is there.