Search code examples
haskellghci

Getting Multiline haskell function to work in ghci


I created this haskell function to remove odd numbers from a list and was trying in ghci. I keep getting the error below though I have enabled the multiline mode and used 4 spaces for indentation.

Prelude> :set +m
Prelude> let removeOdds nums =
Prelude|     if null nums
Prelude|     then []
Prelude|     else
Prelude|         if (mod (head nums)/2) == 0
Prelude|         then (head nums) : (removeOdds(tail nums))
Prelude|         else removeOdds(tail nums)
Prelude| 

:11:5: parse error (possibly incorrect indentation or mismatched brackets)

I read this page about the common mistable newbie's will make and I changed my code as below

Prelude> let removeOdds nums =
Prelude|     do if null nums
Prelude|         then []    
Prelude|         else 
Prelude|           do if mod((head nums)/2) == 0
Prelude|               then head nums: removeOdds(tail nums)   
Prelude|               else removeOdds(tail nums)
Prelude| 

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

Now I ended with a new error. It appears the indentation is a tough thing to get around in haskell.


Solution

  • Your if statement needs to be indented at least one more space:

    Prelude> let removeOdds nums =
    Prelude|      if null nums
    
    Complete example:
    
    Prelude> let removeOdds nums =
    Prelude|      if null nums
    Prelude|      then []
    Prelude|      else
    Prelude|          if (mod (head nums) 2) == 0
    Prelude|          then (head nums) : (removeOdds(tail nums))
    Prelude|          else removeOdds(tail nums)
    Prelude|
    Prelude>