Theory and Design of PL (CS 538)
March 4, 2020
Randomly generate test cases!
cabal v2-install --lib QuickCheck
Inverse property: printing data, then parsing it back should give original data!
Gen a
: something that can generate random a
’sa
, build generator that always returns vala
’s) and use to select the next generator (of b
’s)-- Turn generator of a into generator of pairs of a
genPairOf :: Gen a -> Gen (a, a)
genPairOf g = do x <- g
y <- g
return (x, y)
-- Turn generator of a into generator of lists of a
vectorOf :: Int -> Gen a -> Gen [a]
vectorOf 0 _ = return []
vectorOf n g = do x <- g
xs <- vectorOf (n - 1) g
return (x:xs)
Arbitrary a
: means a
is “generatable”Gen a
Gen a
a
’s and property of a
’sThink: an s \times t contains an s AND a t
-- Declaring a record type
data RecordType = MkRt { getBool :: Bool, getInt :: Int }
myRecord :: RecordType
-- Building records
myRecord = MkRt { getBool = True, getInt = 1234 }
-- Using records via accessors
myBool = getBool myRecord -- True
myInt = getInt myRecord -- 1234
-- Using records pattern match
myFoo = case myRecord of
MkRt { getBool = b, getInt = i } -> ... b ... i ...
Think: an s + t contains an s OR a t
-- Sum types look like this:
data BoolPlusInt = Inl Bool | Inr Int
-- Building sums: two ways
myBool = Inl True :: BoolPlusInt
myInt = Inr 1234 :: BoolPlusInt
-- Using sums: pattern match
myFun :: BoolPlusInt -> String
myFun bOrI = case bOrI of
Inl b -> "Got bool: " ++ (show b)
Inr i -> "Got int: " ++ (show i)
More care needed for non-termination
(Course theme: we won’t be careful)
derive
work?)