Saturday 30 April 2016

Haskell: case expressions


My previous post I explained about piece wise definitions, in this post, I am going to explain case expressions, which are an alternative to if-else if statement, guards and piece wise definitions.

Syntax
f x = case x of
    value1 -> result1
    value2 -> result2
    _ -> defualt_result

‘_’ is a catch-all condition, which matches to all failed scenarios.

Suppose following are the points assigned to students based on their grade.
Grade
Points
1
10
2
9
3
8
4
4
5
3
6
2
7
1
8
0

By using if-else if-else  ladder, you can write the application like below.

getPoints.hs
getPoints :: Int -> Int
getPoints grade = 
    if grade == 1
        then
            10
    else if (grade == 2)
        then 
            9
    else if (grade == 3)
        then
            8
    else if (grade == 4)
        then
            4
    else if (grade == 5)
        then
            3
    else if (grade == 6)
        then
            2
    else if (grade == 7)
        then
            1
    else if (grade == 8)
        then
            0
    else
        -1

*Main> :load getPoints.hs
[1 of 1] Compiling Main             ( getPoints.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> getPoints 1
10
*Main> getPoints 2
9
*Main> getPoints 3
8
*Main> getPoints 4
4
*Main> getPoints 5
3
*Main> getPoints 6
2
*Main> getPoints 7
1
*Main> getPoints 8
0
*Main> getPoints 9
-1
*Main> getPoints (-10)
-1


Same program can be rewritten using case expression like below.

caseEx.hs
getPoints :: Int -> Int
getPoints grade = case grade of
    1 -> 10
    2 -> 9
    3 -> 8
    4 -> 4
    5 -> 3
    6 -> 2
    7 -> 1
    8 -> 0
    _ -> -1

*Main> :load caseEx.hs
[1 of 1] Compiling Main             ( caseEx.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> getPoints 1
10
*Main> getPoints 10
-1
*Main>


You can match case expression against different patterns. Following function displays different messages based on the number of elements in the list.

Number of elements in List
Message
0
The list is empty
1
List has one element
2
List has two elements
>2
List has more than two elements

infoList.hs
info myList = case myList of
    ([]) -> "The list is empty"
    (x:[]) -> "List has one element"
    (x:y:[]) -> "List has two elements"
    (x:y:_) -> "List has more than two elements"

*Main> :load infoList.hs
[1 of 1] Compiling Main             ( infoList.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> info []
"The list is empty"
*Main> 
*Main> info [2]
"List has one element"
*Main> 
*Main> info [2, 3]
"List has two elements"
*Main> 
*Main> info [2, 3, 5]
"List has more than two elements"
*Main> 
*Main> info [2, 3, 5, 7]
"List has more than two elements"


Previous                                                 Next                                                 Home

No comments:

Post a Comment