Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Indentation issue

I am using Visual Studio Code as the text editor of chice and the following Haskell code does not compile. Apperently due to indentation or missing parentheses mistake. Since there are no parenthesies I wonder where the problem is

safeSqrt :: Either String Doubble -> Either String | Doubble
safeSqrt sx =
     case sx of
         Left str -> Left str
         Right x -> if x < 0
             then Left "Error"
             else Right $ sqrt x

The GHCi throws the following error message:

Main.hs:51:1: error:
    parse error (possibly incorrect indentation or mismatched brackets)
   |
51 | safeSqrt sx =    
   | ^

Can enybody help

Thanks

Tom

like image 924
Tom Avatar asked Nov 16 '19 17:11

Tom


People also ask

Is Haskell indentation sensitive?

No, Haskell indentation is not like Python. Haskell is not about indentation levels, it's all about making things line up with other things.

Does indentation matter Haskell?

Even though the consensus among Haskell programmers is that meaningful indentation leads to better-looking code, understanding how to convert from one style to the other can help understand the indentation rules.

How do I fix parse error in Haskell?

The easiest solution to this is to add another pattern instead of your guard. P.S. Repeatedly appending to the end of a list is not very efficient. In fact, it's O(n2). You might want to add to the front instead and reverse the list when you're done.

Does Haskell have significant whitespace?

Languages in which the amount of whitespace can have syntactic meaning. The predominant case of this is "column formatting", in which the horizontal position of the first non-whitespace character is important; FORTRAN, Python, and Haskell fall into this category.


1 Answers

The problem is not with the indentation. It is with the type signature. You used a pipe character (|) in the signature for Either. You should remove that. Furthermore you misspelled Doubble. While a double with double b is nice, it is unfortunately not the name of a Double:

safeSqrt :: Either String Double -> Either String Double
safeSqrt sx =
     case sx of
         Left str -> Left str
         Right x -> if x < 0
             then Left "Error"
             else Right $ sqrt x
like image 121
Willem Van Onsem Avatar answered Oct 19 '22 19:10

Willem Van Onsem