Strange error in haskell about indentation if-then-else

I have the following code:

foo :: Int -> [String] -> [(FilePath, Integer)] -> IO Int foo _ [] _ = return 4 foo _ _ [] = return 5 foo n nameREs pretendentFilesWithSizes = do result <- (bar n (head nameREs) pretendentFilesWithSizes) if result == 0 then return 0 -- <========================================== here is the error else foo n (tail nameREs) pretendentFilesWithSizes 

I get an error in the line with the comment above, error:

 aaa.hs:56:2: parse error (possibly incorrect indentation) 

I work with emacs, there are no spaces, and I do not understand what I was doing wrong.

+7
indentation functional-programming haskell
source share
2 answers

The indents then and else aligned one level more. However, Conditional and do -notation may change.

+8
source share

This is explained in the < if -within- do section of the Wikibooks article on Haskell indentation.

The problem is that for do -desugarer, then and else lines look like new instructions:

 do { first thing ; if condition ; then foo ; else bar ; third thing } 

Indentation in the lines then and else solve the problem.

UPDATE:. Since this is tagged with beginner , I will also note that in Haskell it is usually considered more idiomatic:

 foo :: Int -> [String] -> [(FilePath, Integer)] -> IO Int foo _ [] _ = return 4 foo _ _ [] = return 5 foo n (r:rs) filesWithSizes = bar nr filesWithSizes >>= checkZero where checkZero :: Int -> IO Int checkZero 0 = return 0 checkZero _ = foo n rs filesWithSizes 

This does the same as your foo , but it avoids do sugar and uses pattern matching instead of head and tail and the if-then-else control structure. Informally >>= here it says: "Output the output of bar... from its IO shell and run it through checkZero , returning the result."

+11
source share

All Articles