Home > Enterprise >  How do I use pattern matching in GHCi?
How do I use pattern matching in GHCi?

Time:06-26

I've got this code:

oof [] = 1
oof [(i,j)] = i j
oof [(i,7),(5,j)] = i*j
oof (_:_:xs) = foo xs

and I typed it into ghci. When I try to execute the expression:

oof [(3,7),(5,2)]

it should make use of the third line and return 6, but I'll get the error message:

Exception: <interactive>:11:1-21: Non-exhaustive patterns in function foo

Why do I get this exception?

CodePudding user response:

You likely typed it one line at a time. You should wrap multi-line statements between :{ and :}, so:

ghci> :{
ghci| oof [] = 1
ghci| oof [(i,j)] = i j
ghci| oof [(i,7),(5,j)] = i*j
ghci| oof (_:_:xs) = oof xs
ghci| :}
ghci> oof [(3,7),(5,2)]
6

If you enter these line-by-line, you each time define a new more locally scoped function oof, that only works with the last defined clause.

  • Related