IggY
IggY

Reputation: 3135

Pattern matching in GHCi

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 ?

Upvotes: 11

Views: 5097

Answers (3)

user3496912
user3496912

Reputation: 385

GHCi allows multi-line input by entering :set +m in the interpreter. See Multiline input section for more details.

Here's an example that demonstrates it:

GHCi, version 8.8.3: https://www.haskell.org/ghc/  :? for help
Prelude> :set +m
Prelude> { incList [] = []
Prelude| ; incList (x:xs) = x+1:incList xs
Prelude| }
Prelude> incList [40, 41, 42]
[41,42,43]
Prelude>

Upvotes: 2

AndrewC
AndrewC

Reputation: 32465

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.

Upvotes: 14

md2perpe
md2perpe

Reputation: 3081

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

Upvotes: 19

Related Questions