(==) :: Integer -> Integer -> Bool
(==) :: Char -> Char -> Bool
(==) :: Bool -> Bool -> Bool
— Similarly for (/=) the not-equal operator.
class ClassName typeVar where
methodName :: type sig containing typeVar — Optional: default implementations
== /= Eq
class Eq a where
(==), (/=) :: a -> a -> Bool
— default implementation for (==)
x == y = not (x /= y)
— default implementation for (/=)
x /= y = not (x == y)
— default implementations deliberately circular so you just have to
— implement one of them to break the cycle
a
instance Eq Bool where — (so a=Bool here)
Bool
False == False
True == True
_ == _
= True
= True
= False
— default implementation for (/=) takes hold
Bool
Eq
Eq
== <= +
foo :: Eq -> Eq -> Bool
bar :: Eq a -> Eq a -> Bool
Table of Contents
:lagelli era esehT .epyt a ton si .epyt a ton si ssalc A :GNINRAW
: rof siht sah yrarbil dradnats eht ,.g.e ,epyt a rof sdohtem eseht tnemelpmi oT ).cte ,rahC ,regetnI rof redlohecalp si ” “ elbairav epyt fo elor eht oS(
:siht ekil seog yrarbil dradnats eht ni noitaralced stI .ssalc eht rednu depuorg era dna sdohteM :elpmaxE
:xatnyS .)”sdohtem“( snoitarepo dedaolrevo fo puorg a seralced ”ssalc epyt“ A
.” fo ecnatsni na si “ yas eW
:nwo ruoy dda nac uoy dna ,tsixe-oc ot eseht lla wolla ot si laog ehT
.snoitarepo elbadaolrevo nwo ruoy eralced nac uoy woh dna ,sepyt nwo ruoy ot meht dnetxe nac uoy woh dna ,sepyt suoirav rof , , ekil snoitcnuf dna srotarepo sdaolrevo lleksaH woH
gnidaolrevo rotarepo—sessalc epyT 2 traP sepyT lleksaH
(==) :: Eq a => a -> a -> Bool
Eq a =>
Eq
a
Bool Eq
— Determine whether the 3 arguments are mutually equal. Needs the user-chosen
— type to be an instance of Eq (supports “==”) but otherwise polymorphic.
eq3 :: Eq a => a -> a -> a -> Bool
eq3 x y z = x==y && y==z
<= < Ord
class Eq a => Ord a where
compare :: a -> a -> Ordering — data Ordering = LT | EQ | GT
(<), (<=), (>), (>=) :: a -> a -> Bool
max, min :: a -> a -> a
— there are default implementations; an instance just has to provide
— compare or <=
Eq a => Ord
Ord
Ord Eq
— Sorting algorithms just need Ord but otherwise polymorphic.
insertionSort :: Ord a => [a] -> [a]
insertionSort [] = []
insertionSort (x:xt) = insert x (insertionSort xt)
where
insert e [] = [e]
insert e xs@(x:xt)
| e <= x = e : xs
| otherwise = x : insert e xt
Eq
Eq
Ord a
Eq a
-- De-duplicating sorting uses both (==) and (<). Type sig just needs Ord.
uniqInsertionSort :: Ord a => [a] -> [a]
uniqInsertionSort [] = []
uniqInsertionSort (x:xt) = insert x (uniqInsertionSort xt)
where
insert e [] = [e]
insert e xs@(x:xt)
| e < x = e : xs
| e == x = xs
| otherwise = x : insert e xt
Table of Contents
ti etirw( tseB .
.)edoc s'esle enoemos morf tropmi ro flesruoy fo ecnatsni na osla si ti taht erusne , fo ecnatsni na epyt a gnikam er'uoy fI
.sessalcbus POO ot detalernu si siht taht eraweb tub ,” fo ssalcbus a si “ yas eW .deilpmi s'ti ,” “ yas ot deen t'nod uoy neht ,” “ yas uoy fi ,serutangis epyt nI
:selgna owt morf dootsrednu fo ecnatsni na osla si fo ecnatsni nA :snaem tI .tnereffid tib a si ” “ sihT
: dellac si ssalc ehT .cte , , :elpmaxe rehtonA sh.2sepyTlleksaH ni
,.g.e ,sdohtem eht gnisu snoitcnuf cihpromylop etirw uoy nehw sraeppa osla rekram sihT . fo ecnatsni na eb tsum fo eciohc s'resu tub cihpromylop :rof rekram si ” “ lanoitidda ehT
:siht ekil kool sessalc edistuo sepyt dohteM . fo ”ssalcbus“ a ton si .”ssalcbus“ a ton si epyt A
sh.2sepyTlleksaH ni
data MyIntegerList = INil | ICons Integer MyIntegerList
deriving Show
data MyList a = Nil | Cons a (MyList a)
deriving Show
Eq ==
instance Eq MyIntegerList where
INil == INil = True
ICons x xs == ICons y ys = x==y && xs==ys
_ == _ = False
instance Eq a => Eq (MyList a) where
— The “Eq a =>” there means I need to use (==) on type a.
— Try omitting it to see what happens.
Nil == Nil
Cons x xs == Cons y ys
_ == _
Show Read
= True
= x==y && xs==ys
— “x==y” is when we need to assume Eq a.
= False
Bounded Enum
[1..n]
data MyType = … deriving (Eq, Ord, Bounded, Enum, Show, Read)
==
Num
Int Integer Rational Float
Complex a a Double Float
+ – * abs
Double
Table of Contents
: ,.g.e,sessalcepytlarevesotnidepuorgerasnoitareporebmuN
.)yllausu ro si ( ,)tniop gnitaofl noisicerp-elbuod( ,)tniop gnitaofl noisicerp-elgnis( , , , sah yrarbil dradnatS
dna tsiLregetnIyM rof evoba smhtirogla emas eht etirw dluow retupmoc eht elpmaxe roF
:siht ekil epyt atad ciarbegla ruoy fo noitinfied eht ta ti tseuqer uoY .ylppa snoitcirtseR .uoy rof neg-otua ot sreffo retupmoc eht os ,sessalc eseht rof secnatsni etirw ot gnirob tub drawrofthgiarts si ti netfO
,)noitaton
eht dniheb era sdohtem sti(
, :sessalc epyt rehto eseht tuo kcehC sh.2sepyTlleksaH ni
sessalC lleksaH dradnatS :3.6 noitceS 0102 lleksaH :ecnerefeR .,
:oot meht no
esu nac ew os fo secnatsni meht ekam s’teL sh.2sepyTlleksaH ni
sepyt rebmun lla :secnatsni , , , :sdohtem emos
sessalc dna sepyt rebmuN
secnatsnI devireD fo noitacfiicepS :11 retpahC 0102 lleksaH :ecnerefeR .tsiLyM
:sepyt tsil nwo ruo denfied ew llaceR
Integral
Fractional
div mod Int Integer
/ recip
Rational Float Double Complex a
let xs :: [Double]
xs = [1, 2, 3]
in sum xs / length xs
sum xs :: Double
length xs :: Int
(/)
sum xs / fromIntegral (length xs)
realToFrac
fromIntegral :: (Integral a, Num b) => a -> b
realToFrac :: (Real a, Fractional b) => a -> b
Rational Complex
epsilon :: (Ord a, Fractional a) => a
epsilon = last notTooSmall
where
halves = iterate (/ 2) 1
notTooSmall = takeWhile (\e -> 1 + e > 1) halves
epsilonDouble :: Double
epsilonDouble = epsilon
epsilonFloat :: Float
epsilonFloat = epsilon
Table of Contents
:ypoc eno tsuj ni dnah ot uoy swolla egaugnal yrotcafsitas A
)!esrow neve rof 886453018081649658/sutats/idnareporehsom/moc.rettiwt//:sptth ees tuB(
.egaugnal diputs a si #C esuaceb sepyt rebmun owt rof edoc emas eht fo seipoc owt etirw ot decrof si 4307552/dlefiraBwerdnA/moc.buhtig.tsig//:sptth
). dna nwo ruoy nettirw evah dluoc uoy ,.g.E( .sessalc tnaveler eht fo ecnatsni na ti gnikam yb epyt rebmun nwo ruoy dda nac uoY
.yrutneC ts12 eht siht ni lanimirc si sihT
.epyt emas eht fo eb ot sdnarepo owt eht stnaw
.nolispe enihcaM :elpmaxE
?rorre epyt a siht si yhW :esicrexE srebmuN :4.6 noitceS 0102 lleksaH :ecnerefeR
, , ,
:secnatsni :sdohtem emos
,
:secnatsni :
,
esu ro :xfi ot woH
:
:rewsnA
,
:sdohtem emos
length :: Foldable t => t a -> Int
length :: [a] -> Int
length :: [a] -> Int
sum :: Num a => [a] -> a
minimum :: Ord a => [a] -> a
— assumes non-empty list
foldr :: (a -> b -> b) -> b -> [a] -> b [a] [] a
Foldable t
Foldable (t a)
sum :: Num a => Vector a -> a
— Vector is an array, 0-based Int index. Third-party but popular library.
— https://hackage.haskell.org/package/vector/
sum :: Num a => Seq a -> a
— Seq is a middle ground between array and linked list,
— O(1) prepend and append, log time random access.
[] Integer [] Char [] String [] a
[] Integer Vector Integer Seq Integer t Integer
Table of Contents
:noitazilareneg fo dnik siht lleksaH dna avaJ htob morf wenk uoY .segaugnal rehto ni nees rofothguohtt’nevahuoyyawanitub,ssalcepytahtiwnoitazilarenegsihtstroppuslleksaH
:elbanosaer osla era eseht ,elpmaxe roF .stsil deknil tsuj ton ,oot secneuqes gnitneserper serutcurts atad rehto rof esnes ekam esehT
.”
:”yrammus“ a etupmoc dna tsil a emusnoc taht snoitcnuf yrarbil wef A “ ton si ti woh dna ” “ ekil sgniht htiw uoy sezirailimaf sihT .2
:ssalc epyt eht si ereh ,taht htiW
:ot , , :morf
:noitazilareneg siht od ot uoy gnillet m’I won tuB
:ot , , :morf
).” “ sa nettirw osla eb nac ” “ :llaceR(
ekil sepyt evah stsil rof snoitcnuf yrarbil eht fo emos yhw snialpxe sihT .1 :dlofowt si noitces siht fo esoprup ehT
relpmis eht fo daetsni
elbadloF
sh.2sepyTlleksaH ni
class Foldable t where
length :: t a -> Int — implicitly ∀a, similarly below sum :: Num a => t a -> a
minimum :: Ord a => t a -> a
foldr :: (a -> b -> b) -> b -> t a -> b
— and others
class Foldable (t a)
instance Foldable ([] a)
instance Foldable []
Ord <=
-- implicitly ∀a,b
template
<=
insertionSort
Table of Contents
:ecafretni na dnetxe ot sah elbairav epyt eht taht setats erutangis epyT
.detpoda ton saw tub ,sessalc epyt s'lleksaH fo enil eht gnola ”tpecnoc“ dellac lasoporp a saw erehT
.segassem rorre roop ,noitalipmoc etarapes staefed :smelborp sti lla dna gnilpuoc thgit tub ,skroW
.ti stroppus epyt nesohc-resu eht kcehc nac , sesu ti ees nac ,)ereht thgir ti dnapxe ot( edoc etalpmet eht ot ssecca sah relipmoc ,etis llac tA .orcam ekil si ”etalpmet“ tuB
++C od segaugnal depyt-yllacitats rehto tahW .secafetni dna sessalc tcartsba POO ,.g.e ,noitcartsba yna fo eurT
.od ot tahw dnim ruoy pu gnikam gnitanitsarcorp ,edoc lautca gnitirw gnitanitsarcorP .eman dohtem nommoC
.cte ,tsuR ,alacS ,avaJ
:epytotorp eht ot egnahc oN
:naht tfieneb rehtruf on rof detaerC :ssalc epyt daB
.smhtirogla eert hcraes yranib dna smhtirogla gnitros fo sisab eht era swal esehT .latot ,cirtemmys-itna ,evitisnart ,evixefler si : :elpmaxE
.smhtirogla lareneg lufesu dliub ot desu eb nac erofereht ,snoitatcepxe ro swal lufesu yfsitas sdohteM
,” “ ekil og secnatsni ,esiwekiL .”
.” “ ton “ ton si tI :tnatropmI
.secnatsni elpitlum evah uoY :stiart eseht sah ssalc epyt doog A
sessalc epyt dab dna sessalc epyt dooG
insertionSort
Sorter
(* Example in OCaml *)
module Sorter(Cmp : sig
type t
insertionSort
val leq : (t,t) -> bool
end)
= struct
let rec insertionSort xs = …
(* insertion sort code; use Cmp.leq to compare *)
end
Sorter
Sorter
(* Example in OCaml *)
module IntCmp = struct
type t = int
let leq (x,y) = x<=y
end
module IntSorter = Sorter(IntCmp)
(* Now can use IntSorter.insertionSort for [int] *)
Comparable
Comparable
Table of Contents
.sredro evitanretla neve ,sepyt tnemele rehto rof ylralimiS
. etaitnatsni ot ti esu ,srotarepo nosirapmoc tni sniatnoc taht eludom a etirw ,stni rof esu oT
.rotarapmoc dna epyt tnemele sefiiceps taht eludom rehtona retemarap sa sekat ti tub— ti llac—eludom a otni tuP
.sdohteM etalpmeT laeR .sretemarap sa seludom rehto ekat nac eludom A
.” dnetxet'nseodepytnesohc-resu“yastsuJ:etisesutasegassemrorredooG
.gis epyt daer ot sdeen ylno ,edoc lanretni troSnoitresni daer ot deen ton seod , sdnetxe epyt nesohc-resu taht skcehc relipmoC :etis esu gnilipmoc nehW
.setis esu wonk ot deen ton seod ,sdohtem nosirapmoc esu ot dewolla si edoC : gnilipmoc nehW
:noitalipmoc etarapes ot yldneirF
:)oot sessalc epyt lleksaH( stfieneb sti lla dna gnilpuoc-ed dooG
).msihpromylop cirtemarap lleksaH morf ti thguorb ohw reldaW lihP morf emac scireneg avaJ ,tcaf nI( .POO ot detpada tub sessalc epyt lleksaH morf denraeL
lmaCO ,lmaC ,LMS