Saturday 30 April 2016

Haskell: Indentations


Unlike other languages (like Java, C, C++), Haskell don't depend on braces {} to represent the code, Haskell uses indentations to reduce the verbosity of your code.

Basic Rule of Indentation is, Code that is part of some expression must be indented further than the beginning of that expression.

letEx.hs
processData x = let a = 10 
                    b = 20
                    c = 30 
                    d = 40 
                 in (a+b+c+d*x)


Above one works fine, since after let expression all the variables are defined with same indentation.

I just defined variable ‘b’ one space before like below.
processData x = let a = 10 
                   b = 20
                    c = 30 
                    d = 40 
                 in (a+b+c+d*x)

When I tried to load processData, I got following error. 
*Main> :load letEx.hs
[1 of 1] Compiling Main             ( letEx.hs, interpreted )

letEx.hs:2:20: parse error on input b
Failed, modules loaded: none.


This kind of errors seems to be crazy for beginners, but trust me after you accustomed to the indentation; you feel the beauty in it.

Following are the different ways to define the let..in block.
processData x = 
    let a = 10 
        b = 20
        c = 30 
        d = 40 
    in (a+b+c+d*x)

processData x = 
    let 
        a = 10 
        b = 20
        c = 30 
        d = 40 
    in (a+b+c+d*x)


If you really want to use semicolons, use curly braces instead of indentation, Haskell allowing it. My next post explains about this.



Previous                                                 Next                                                 Home

No comments:

Post a Comment