Saturday 30 April 2016

Haskell: if else expression


You can take decision by using if-else construct. If the condition evaluates to true, then the bock of code in if block executes, else the code in else bock will execute. Only difference between the if statement in imperative languages and Haskell is, if expression in Haskell must followed by an else statement, where as in other languages like Python, Java it is optional. In Haskell, every construct is an expression, expression must return a value, so if expression must has else part, so it can return value on both True and False cases.

Syntax
if condition
    then
      statements
else
    statements

For example, following function isEven takes a number and return True, if the number is even else False.

if.hs
isEven num = 
    if (num `rem` 2) == 0
        then 
            True
    else False

*Main> :load if.hs
[1 of 1] Compiling Main             ( if.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> isEven 100
True
*Main> isEven 101
False
*Main> isEven 102
True


In Haskell, if statements are also expressions.

*Main> [if 15 > 13 then "Woo" else "Boo", if 'x' > 'y' then "Foo" else "Bar"]
["Woo","Bar"]

How if-else construct differ from other languages?
In Haskell, everything is evaluated as expression including if-then-else. So if statement must always preceded by else construct.

If ‘if’ block return a value of type ‘t’, then ‘else’ block also must return the value of type t.

if.hs
isEven num = 
    if (num `rem` 2) == 0
        then 
            True
    else "Odd Number"


Try to load above program, you will get following error.
Prelude> :load if.hs
[1 of 1] Compiling Main             ( if.hs, interpreted )

if.hs:5:10:
    Couldn't match expected type Bool with actual type [Char]
    In the expression: "Odd Number"
    In the expression:
      if (num `rem` 2) == 0 then True else "Odd Number"
    In an equation for isEven:
        isEven num = if (num `rem` 2) == 0 then True else "Odd Number"
Failed, modules loaded: none.




Previous                                                 Next                                                 Home

No comments:

Post a Comment