dsaxton
dsaxton

Reputation: 1015

Indentation problems in GHCi

I'm learning Haskell and keep getting these indentation errors when I try to define functions over multiple lines in GHCi. Here's an attempt to redefine the elem function:

λ: :{
| let elem' x xs
|     | null xs = False
|     | x == head xs = True
|     | otherwise = elem' x (tail xs)
| :}

<interactive>:15:5: error:
    parse error (possibly incorrect indentation or mismatched brackets)

Do the = signs somehow need to be aligned?

Upvotes: 0

Views: 719

Answers (2)

chi
chi

Reputation: 116174

A let indented like this

let elem' x xs
    | null xs = False
    | x == head xs = True
    | otherwise = elem' x (tail xs)

is a let with four entries much like

let x1 = ...
    x2 = ...
    x3 = ...
    x4 = ...

if you want to continue a previous entry, rather than starting a new one, you should indent it more. The rule is the same in source files and in GHCi. The indentation rule might look a bit mysterious at the beginning but it's actually fairly simple.

Upvotes: 0

duplode
duplode

Reputation: 34398

You need to indent the guards further. If you leave them at the same indentation than the elem' name, GHC(i) will attempt to parse them as additional definitions within the let-block, and not as part of the definition of elem:

let elem' x xs
        | null xs = False
        | x == head xs = True
        | otherwise = elem' x (tail xs)

If you are using GHC 8 or above, you don't need a let for defining things in GHCi, so this (between :{ and :}, as before) will just work:

elem' x xs
    | null xs = False
    | x == head xs = True
    | otherwise = elem' x (tail xs)

Upvotes: 2

Related Questions