Pattern matching in GHCi

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.


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>

Tags:

Haskell