开发者

Haskell Error: parse error on input `='

Specs

GHC 6.12.1

Mac OS X 10.6.4 x64

MacBook Pro

Problem

I'm having trouble using let syntax. The following code refuses to compile:

module Main where

main = let x = 1
        y = 2
        z = 3
    in putStrLn $ "X = " ++ show x ++ "\nY = " ++开发者_开发知识库 show y ++ "\nZ = " ++ show z

I tried tabbing in y = 2 and z = 3 even more. No dice.

(Undesirable) Solutions

The only way I've gotten the code to compile is either

  1. Replacing hard tabs with spaces.
  2. Replacing the let clause with a where clause.


Saizan on #haskell explains that the assignments in a let expression have to align, not let itself. As long as the assignments line up, it's okay to use hard tabs or soft tabs.

Correct code:

module Main where

main = let
        x = 1
        y = 2
        z = 3
    in putStrLn $ "X = " ++ show x ++ "\nY = " ++ show y ++ "\nZ = " ++ show z


You simply can't control indentation correctly with tabs because the size of a tab is undefined.

Therefore, don't use tabs in Haskell. They're evil.


Indent each declaration in the let-block to the same degree. Also good form is to indent the 'in' and 'let' to the same level. Eg..

main = let x = 1
           y = 2
           z = 3
       in putStrLn $ "X = " ++ show x ++ "\nY = " ++ show y ++ "\nZ = " ++ show z


Personally, I put semicolon at the end of each line

module Main where

main = let x = 1 ;
           y = 2 ;
           z = 3 
in putStrLn $ "X = " ++ show x ++ "\nY = " ++ show y ++ "\nZ = " ++ show z


If you insist on TAB characters in your source, the following compiles:

module Main where

main =
    let x = 1
        y = 2
        z = 3
    in putStrLn $ "X = " ++ show x ++ "\nY = " ++ show y ++ "\nZ = " ++ show z

where all leading whitespace is either one or two TABs, and the whitespace between let and x = 1 is also a TAB. Viewed in vi's list mode to make TABs and line-ends explicit:

module Main where$
$
main =$
^Ilet^Ix = 1$
^I^Iy = 2$
^I^Iz = 3$
^Iin putStrLn $ "X = " ++ show x ++ "\nY = " ++ show y ++ "\nZ = " ++ show z$

Your life will be much simpler and your code prettier if you switch to spaces.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜