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
No, Haskell indentation is not like Python. Haskell is not about indentation levels, it's all about making things line up with other things.
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.
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.
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.
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 . While a double with double b is nice, it is unfortunately not the name of a Doubble
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With