0

I'm trying to declare an immutable variable in Haskell:

let a = [1, 2]
main = print $ sum a

but it claims

parse error (possibly incorrect indentation)

what's up with that?

1 Answer 1

14

let is not used at the top level definition. There are several ways to correct your programs, some of which are

a = [1,2]
main = print $ sum a

Or

main = do
  let a = [1,2]
  print $ sum a

Or

main = let a = [1,2] in print $ sum a

The usual source of confusion for people trying to use let at the top level is when they are trying to convert some tested expression in ghci to actual source file.

let can be used when you are working inside a monad. ghci and main works inside IO monad, so you can write something like let a = [1,2] in ghci.

Sign up to request clarification or add additional context in comments.

6 Comments

I'm not doing it inside ghci or main.
why are you saying that if it won't help me?
The comment about ghci is something extra which usually confuse people who try to convert expression tested in ghci into haskell programs.
let is also used for let ... in ... expressions, e.g. main = let a = [1,2] in print $ sum a would be another valid alternative.
StackOverflow is a collaboratively edited Q&A site, not a one on one tutoring site. By providing an explanation for all of the cases when and when not to use the let construct, this answer is more useful to anyone who happens to see this question when trying to find information about that syntax.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.