Pergunta

I am a beginner in Haskell and want to start solving problems with it, so I tried to solve the very first SPOJ problem (problem code: TEST). The "problem" is to read lines and print them until "42" comes up.

main = do input <- getLine
          if input == "42" then putStr "" 
          else do putStrLn input
                  main

My solution is very simple, but I get a parse error on input 'if'. Everything works just fine when I change 'main' to 'main2' at the beginning and in the else-statement. Why is there a parse error on 'if'?

Foi útil?

Solução

Your editor mixes tabs and spaces, and while your editor shows a tab as 4 spaces, Haskell interprets a tab as 8 character.

Note that you cannot reproduce your code here on StackOverflow in a normal code block, since StackOverflow automatically replaces tabs with spaces. Try for yourself - copy the code from your question into your editor, assuming it doesn't automatically transform spaces at the beginning into tabs.

So disable tabs in your editor and convert existing tabs to four spaces and you should be fine.

Outras dicas

Try indenting the "else" more on the right than the "if". This is no longer required now (IIRC), but earlier compilers required that. The reason is that in a do block your code is parsed as:

main = do { input <- getLine ;
            if input == "42" then putStr "" ;  -- parse error, no "else"
            else do { putStrLn input ;
                      main
                    }
          }

New compilers should allow the extra ";" beofre the "else", older ones do not.

For more details see DoIfThenElse.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top