Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching in GHCi

Tags:

haskell

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 ?

like image 350
IggY Avatar asked Mar 31 '13 18:03

IggY


People also ask

Can you pattern match in guards Haskell?

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 | .

What is pattern matching explain with example?

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.

How is pattern matching done in Haskell?

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.


2 Answers

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
like image 153
md2perpe Avatar answered Oct 12 '22 23:10

md2perpe


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.

like image 40
AndrewC Avatar answered Oct 13 '22 01:10

AndrewC