Search code examples
haskellindentationghci

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?


Solution

  • 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)