In school exercice
I have this Function
bar :: Float -> Float -> Float
bar x 0 = 0
bar 0 y = 0
bar x y = x * y
I type it in GHC as
let bar x 0 = 0; bar 0 y = 0; bar x y = x * y
and evaluate
bar foo 0
bar 0 foo
I'm asked to modify bar to use '|' so I want to do something like :
let bar x y = | x 0 = 0 | 0 y = 0 | x y = x * y
but in ghci I got
parse error on input '='
How can I do it in GHCi ? Will the fact of using pattern matching ('|') change something ?
The PatternGuards extension, now officially incorporated into the Haskell 2010 language, expands guards to allow arbitrary pattern matching and condition chaining. The existing syntax for guards then becomes a special case of the new, much more general form. You start a guard in the same way as always, with a | .
Pattern matching is the process of checking whether a specific sequence of characters/tokens/data exists among the given data. Regular programming languages make use of regular expressions (regex) for pattern matching.
Overview. We use pattern matching in Haskell to simplify our codes by identifying specific types of expression. We can also use if-else as an alternative to pattern matching. Pattern matching can also be seen as a kind of dynamic polymorphism where, based on the parameter list, different methods can be executed.
Look at the syntax for using guards:
bar x y | x == 0 = 0
| y == 0 = 0
| otherwise = x * y
Written on one line in GHCi:
let bar x y | x == 0 = 0 | y == 0 = 0 | otherwise = x * y
Use files
Don't type your code directly into ghci unless it really is a one-liner.
Save your code in a text file called PatternMatch.hs and load it in ghci by typing.
:l PatternMatch.hs
and then if you make changes (and save) you can reload the file in ghci by typing
:r
Alternatively, you could name your files after which exercise they are in, or just have a reusablle Temp.hs if it really is throwaway code.
By saving stuff in a text file you make it much more easily editable and reusable.
Modules
Later you'll collect related functions together using a proper module, so they can be importer into other programs. For example, you could have
module UsefulStuff where
pamf = flip fmap
saved in a file called UsefulStuff.hs and then in another file you could
import UsefulStuff
and then use the functions from UsefulStuff there.
Modules are overkill for what you're doing now, but getting the workflow of edit, save, recompile, test, repeat, you'll save yourself from quite a bit of effort.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With