We'll be using the interactive system associated with ghc. Start your editor, and create a file Exercises.hs containing
module Exercises where factorial n = product [1..n] |
Start ghci: On a CS Unix machine, use the command
"/usr/local/bin/ghci". You will see the following:
> ghci ___ ___ _ / _ \ /\ /\/ __(_) / /_\// /_/ / / | | GHC Interactive, version 6.2, for Haskell 98. / /_\\/ __ / /___| | http://www.haskell.org/ghc/ \____/\/ /_/\____/|_| Type :? for help. Loading package base ... linking ... done. Prelude> |
Now load module Exercises into the system, and test the definition of factorial.
Prelude> :l Exercises Compiling Exercises ( Exercises.hs, interpreted ) Ok, modules loaded: Exercises. *Exercises> factorial 6 720 *Exercises> |
To reload the module, use the command ":r". Once this works, you can experiment with small function definitions. A useful command to know is ":i", which displays information about any name.
*Exercises> :i factorial -- factorial is a variable, defined at Exercises.hs:3 factorial :: forall a. (Num a, Enum a) => a -> a *Exercises> |
(In this case, we discover that factorial is overloaded, and can be used at any type which is both numeric and enumerable, the latter because we used an enumeration [1..n] in its definition).
type Set a = [a] isSubset :: Eq a => Set a -> Set a -> Bool sameSet :: Eq a => Set a -> Set a -> Bool powerSet :: Set a -> Set (Set a) union :: Eq a => Set a -> Set a -> Set a intersection :: Set a -> Set a -> Set a setProduct :: Set a -> Set b -> Set (a,b) disjointUnion :: (Eq a, Eq b) => Set a -> Set b -> Set (Either a b, Either a b) setDifference :: Eq a -> Set a -> Set a -> Set a *Exercises> disjointUnion [1,2,3] [1,2] [(Left 1,Right 1),(Left 1,Right 2), (Left 2,Right 1),(Left 2,Right 2), (Left 3,Right 1),(Left 3,Right 2)] |
type Relation a b = Set (a,b) composeRelations :: Relation a b -> Relation b c -> Relation a c isReflexive :: Eq a => Set a -> Relation a a -> Bool isSymmetric :: Eq a => Relation a a -> Bool isTransitive :: Eq a => Relation a a -> Bool isEquivalence :: Eq a => Set a -> Relation a a -> Bool -- Examples of relations r1 = [(a,a) | a <- [0..10]] r2 = [(a,b) | a <- [0..10], b <- [0..10], b > a] r3 = [(a,a+1) | a <- [0..10]] *Exercises> isReflexive [1..10] r1 True *Exercises> isSymmetric r2 False |