Curious
Curious

Reputation: 921

haskell indentation issue with do and let ..in statements

I tried various combinations to fix the indentation for the following code but failed. How shall i fix the below

fold' list = do
    let result = foldl (+) list
    in putStrLn $ "Reduced " ++ show(result)
    return $ result

 parse error on input `in'
Failed, modules loaded: none.

Upvotes: 1

Views: 72

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477210

In a do clause, the in keyword should not be used.

So you can fix it with writing:

fold' list = do
    let result = foldl (+) list
    putStrLn $ "Reduced " ++ show(result)   -- no "in" keyword
    return $ result

The scope of the let statement is the rest of the clauses.

The translation is like specified in section 3.14 of the Haskell report [link]:

do {e}                =   e
do {e;stmts}          =   e >> do {stmts}
do {p <- e; stmts}    = let ok p = do {stmts}
                            ok _ = fail "..."
                        in e >>= ok
do {let decls; stmts} =   let decls in do {stmts}

So in case we define two let statements with the same name (which is not recommended), the first one moving to the top will count.

So for:

foo = do
    let x = "4"
    putStrLn x
    let x = "2"
    putStrLn x

It will translate into:

foo = let x = "4" in (putStrLn x >> (let x = "2" in putStrLn x))

So the first putStrLn will use the x defined by let x = "4" whereas the last one will use the x defined in let x = "2".

Upvotes: 4

Related Questions