Saturday, 30 April 2016

Haskell: wildcard pattern


Underscore character (_) matches anything.

BookUtil.hs
type ISBN = String
type Title = String
type Authors = [String]

data BookInfo = Book ISBN Title Authors 

getIsbn :: BookInfo -> ISBN
getIsbn (Book isbn _ _) = isbn

getTitle :: BookInfo -> Title
getTitle (Book _ title _) = title

getAuthors :: BookInfo -> Authors
getAuthors (Book _ _ authors) = authors

*Main> :load BookUtil.hs
[1 of 1] Compiling Main             ( BookUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> let bk1 = Book "123SVC" "Java Tutorial" ["Krishna", "Hari"]
*Main> 
*Main> getIsbn bk1
"123SVC"
*Main> 
*Main> getTitle bk1
"Java Tutorial"
*Main> 
*Main> getAuthors bk1
["Krishna","Hari"]
*Main> 


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

pointsCals.hs
pointsforGrade 1 = 10
pointsforGrade 2 = 9
pointsforGrade 3 = 8
pointsforGrade 4 = 4
pointsforGrade 5 = 3
pointsforGrade 6 = 2
pointsforGrade 7 = 1
pointsforGrade 8 = 0
pointsforGrade _ = -1
 
‘_’ is a special wild card character, it matches with anything.
*Main> :load pointsCalc.hs
[1 of 1] Compiling Main             ( pointsCalc.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> pointsforGrade 1
10
*Main> pointsforGrade 2
9
*Main> pointsforGrade 3
8
*Main> pointsforGrade 4
4
*Main> pointsforGrade 5
3
*Main> pointsforGrade 6
2
*Main> pointsforGrade 7
1
*Main> pointsforGrade 8
0
*Main> pointsforGrade 9
-1
*Main> pointsforGrade (-10)
-1
*Main> 


Always kept the ‘_’ character at end, if you kept the _ character at starting of your logic, it matches to all. For example, I updated pointsCalc.hs like below.

pointsCalc.hs
pointsforGrade _ = -1
pointsforGrade 1 = 10
pointsforGrade 2 = 9
pointsforGrade 3 = 8
pointsforGrade 4 = 4
pointsforGrade 5 = 3
pointsforGrade 6 = 2
pointsforGrade 7 = 1
pointsforGrade 8 = 0

*Main> :load pointsCalc.hs
[1 of 1] Compiling Main             ( pointsCalc.hs, interpreted )

pointsCalc.hs:1:1: Warning:
    Pattern match(es) are overlapped
    In an equation for pointsforGrade:
        pointsforGrade 1 = ...
        pointsforGrade 2 = ...
        pointsforGrade 3 = ...
        pointsforGrade 4 = ...
        ...
Ok, modules loaded: Main.
*Main> 
*Main> pointsforGrade 1
-1
*Main> pointsforGrade 2
-1
*Main> pointsforGrade 3
-1


Observe I am getting -1 for all the grades, it is because I kept ‘_’ symbol at starting of my logic, so it matches to all.

 
Previous                                                 Next                                                 Home

No comments:

Post a Comment