





Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!






M. Al-hassy April 2020
Hello, Home!
main = do putStr "What’s your name? " name <- getLine putStrLn ("It’s 2020, " ++ name ++ "! Stay home, stay safe!")
Pattern Matching
Functions can be defined using the usual if_then_else_ construct, or as expressions guarded by Boolean expressions as in mathematics, or by pattern matching —a form of ‘syntactic comparision’.
fact n = if n == 0 then 1 else n * fact (n - 1)
fact’ n | n == 0 = 1 | n != 0 = n * fact’ (n - 1)
fact’’ 0 = 1 fact’’ n = n * fact’’ (n - 1)
The above definitions of the factorial function are all equal.
Guards, as in the second version, are a form of ‘multi-branching conditional’.
In the final version, when a call, say, fact 5 happens we compare syntactically whether 5 and the first pattern 0 are the same. They are not, so we consider the second case with the understanding that an identifier appearing in a pattern matches any argument, so the second clause is used.
Hence, when pattern matching is used, order of equations matters: If we declared the n-pattern first, then the call fact 0 would match it and we end up with 0 * fact (-1), which is not what we want!
If we simply defined the final fact using only the first clause, then fact 1 would crash with the error Non-exhaustive patterns in function fact. That is, we may define partial functions by not considering all possible shapes of inputs.
See also “view patterns”.
Local Bindings
An equation can be qualified by a where or let clause for defining values or functions used only within an expression.
...e...e...e where e = expr ≈ let e = expr in ...expr ...expr ...expr
It sometimes happens in functional programs that one clause of a function needs part of an argument, while another operators on the whole argument. It it tedious (and inef- ficient) to write out the structure of the complete argument again when referring to it. Use the “as operator” @ to label all or part of an argument, as in
f label@(x:y:ys) = · · ·
Operators
Infix operators in Haskell must consist entiry of ‘symbols’ such as &, ^, !, ... rather than alphanumeric characters. Hence, while addition, +, is written infix, integer division is written prefix with div.
We can always use whatever fixity we like: If f is any prefix binary function, then x ‘f‘ y is a valid infix call. If ⊕ is any infix binary operator, then (⊕) x y is a valid prefix call.
It is common to fix one argument ahead of time, e.g., λ x → x + 1 is the successor operation and is written more tersely as (+1). More generally, (⊕r) = λ x → x ⊕ r.
The usual arithmeic operations are +, /, *, - but % is used to make fractions.
The Boolean operations are ==, /=, &&, || for equality, discrepancy, conjunction, and disjunction.
Types
Type are inferred, but it is better to write them explicitly so that you communicate your intentions to the machine. If you think that expression e has type τ then write e :: τ to communicate that to the machine, which will silently accept your claim or reject it loudly. Type Name Example Value Small integers Int 42 Unlimited integers Integer 7376541234 Reals Float 3.14 and 2 % 5 Booleans Boolean True and False Characters Char ’a’ and ’3’ Strings String "salam" Lists [α] [] or [x 1 , ..., xn] Tuples (α, β, γ) (x 1 , x 2 , x 3 ) Functions α → β λ x → · · ·
Polymorphism is the concept that allows one function to operate on different types. A function whose type contains variables is called a polymorphic function. The simplest polymorphic function is id : : a -> a, defined by id x = x.
Tuples
Tuples (α 1 , ..., αn) are types with values written (x 1 , ..., xn) where each xi :: αi. The are a form of ‘record’ or ‘product’ type.
E.g., (True, 3, ’a’) :: (Boolean, Int, Char).
Tuples are used to “return multiple values” from a function.
Two useful functions on tuples of length 2 are:
fst :: (α, β) → α fst (x, y) = x
snd :: (α, β) → β snd (x, y) = β
If in addition you import Control.Arrow then you may use:
first :: (α → τ ) → (α, β) → (τ , β) first f (x, y) = (f x, y)
second :: (β → τ ) → (α, β) → (α, τ ) second g (x, y) = (x, g y)
(***) :: (α → α’) → (β → β) → (α, β) → (α’, β’) (f *** g) (x, y) = (f x, g y)
(&&&) :: (τ → α) → (τ → β) → τ → (α, β) (f &&& g) x = (f x, g x)
Lists
Lists are sequences of items of the same type. If each xi : : α then [x 1 , ..., xn] : : [α].
Lists are useful for functions that want to ‘non-deterministicly’ return a value: They return a list of all possible values.
The empty list is [] We “cons”truct nonempty lists using (:) : : α → [α] → [α] Abbreviation: [x 1 , ..., xn] = x 1 : (x 2 : (· · · (xn : []))) List comprehensions: [f x | x <- xs, p x] is the list of elements f x where x is an element from list xs and x satisfies the property p ◦ E.g., [2 * x | x <- [2, 3, 4], x < 4] ≈ [2 * 2, 2 * 3] ≈ [4, 6] Shorthand notation for segments: u may be ommitted to yield infinite lists ◦ [l .. u] = [l, l + 1, l + 2, ..., u]. ◦ [a, b, .., u] = [a + i * step | i <- [0 .. u - a] ] where step = b - a
Strings are just lists of characters: "c 0 c 1 ...cn" ≈ [’c 0 ’, ..., ’cn’].
Hence, all list methods work for strings.
Pattern matching on lists
prod [] = 1 prod (x:xs) = x * prod xs
fact n = prod [1 .. n]
If your function needs a case with a list of say, length 3, then you can match directly on that shape via [x, y, z] —which is just an abbreviation for the shape x:y:z:[].
Likewise, if we want to consider lists of length at least 3 then we match on the shape x:y:z:zs. E.g., define the function that produces the maximum of a non-empty list, or the function that removes adjacent duplicates —both require the use of guards.
[x 0 , ..., xn] !! i = xi [x 0 , ..., xn] ++ [y 0 , ..., ym] = [x 0 , ..., xn, y 0 , ..., ym] concat [xs 0 , ..., xsn] = xs 0 ++ · · · ++ xsn
{- Partial functions -} head [x 0 , ..., xn] = x 0 tail [x 0 , ..., xn] = [x 1 , ..., xn] init [x 0 , ..., xn] = [x 0 , ..., xn− 1 ] last [x 0 , ..., xn] = xn
take k [x 0 , ..., xn] = [x 0 , ..., xk − 1 ] drop k [x 0 , ..., xn] = [xk , ..., xn]
sum [x 0 , ..., xn] = x 0 + · · · + xn prod [x 0 , ..., xn] = x 0 * · · · * xn reverse [x 0 , ..., xn] = [xn, ..., x 0 ] elem x [x 0 , ..., xn] = x == x 0 || · · · || x == xn
zip [x 0 , ..., xn] [y 0 , ..., ym] = [(x 0 , y 0 ), ..., (xk , yk )] where k = n ‘min‘ m unzip [(x 0 , y 0 ), ..., (xk , yk )] = ([x 0 , ..., xk ], [y 0 , ..., yk ])
Duality: Let ∂f = reverse. f. reverse, then init = ∂ tail and take k = ∂ (drop k); even pure. head = ∂ (pure. last) where pure x = [x].
List ‘Design Patterns’
Many functions have the same ‘form’ or ‘design pattern’, a fact which is taken advan- tage of by defining higher-order functions to factor out the structural similarity of the individual functions.
map f xs = [f x | x <- xs] Transform all elements of a list according to the function f.
filter p xs = [x | x <- xs, p x] Keep only the elements of the list that satisfy the predicate p. takeWhile p xs ≈ Take elements of xs that satisfy p, but stop stop at the first element that does not satisfy p. dropWhile p xs ≈ Drop all elements until you see one that does not satisfy the predicate. xs = takeWhile p xs ++ dropWhile p xs.
Right-folds let us ‘sum’ up the elements of the list, associating to the right.
foldr (⊕) e ≈ λ (x 0 : (x 1 : (... : (xn : [])))) → (x 0 ⊕ (x 1 ⊕ (... ⊕ (xn ⊕ e))))
This function just replaces cons “:” and [] with ⊕ and e. That’s all. E.g., replacing :,[] with themselves does nothing: foldr (:) [] = id.
Common Typeclasses Show Show elements as strings, show Read How to read element values from strings, read Eq Compare elements for equality, == Num Use literals 0, 20, ..., and arithmetic +, *, - Ord Use comparison relations >, <, >=, <= Enum Types that can be listed, [start .. end] Monoid Types that model ‘(untyped) composition’ Functor Type formers that model effectful computation Applicative Type formers that can sequence effects Monad Type formers that let effects depend on each other
The Ord typeclass is declared class Eq a => Ord a where · · · , so that all ordered types are necessarily also types with equality. One says Ord is a subclass of Eq; and since sub- classes inherit all functions of a class, we may always replace (Eq a, Ord a) => · · · by Ord a => · · ·.
You can of-course define your own typeclasses; e.g., the Monoid class in Haskell could be defined as follows.
class Semigroup a where (<>) :: a -> a -> a {- A way to “compose” elements together -} {- Axiom: (x <> y) <> z = x <> (y <> z) -}
class Semigroup a => Monoid a where mempty :: a {- Axiom: This is a ‘no-op’, identity, for composition <> -}
Example monoids (α, <>, mempty) include (Int, +, 0), ([α], ++, []), and (Program statements, sequence “;”, the empty statement) —this last example is approx- imated as Term with ‘let-in’ clauses at the end of this cheatsheet. Typeclasses are inter- faces, possibly with axioms specifying their behaviour.
As shown earlier, Haskell provides a the deriving mechanism for making it easier to define instances of typeclasses, such as Show, Read, Eq, Ord, Enum. How? Constructor names are printed and read as written as written in the data declaration, two values are equal if they are formed by the same construction, one value is less than another if the constructor of the first is declared in the data definition before the constructor of the second, and similarly for listing elements out.
Functor
Functors are type formers that “behave” like collections: We can alter their “ele- ments” without messing with the ‘collection structure’ or ‘element positions’. The well- behavedness constraints are called the functor axioms.
class Functor f where fmap :: (α → β) → f α → f β
(<$>) = fmap {- An infix alias -}
The axioms cannot be checked by Haskell, so we can form instances that fail to meet the implicit specifications —two examples are below.
Identity Law: fmap id = id
Doing no alteration to the contents of a collection does nothing to the collection.
This ensures that “alterations don’t needlessly mess with element values” e.g., the follow- ing is not a functor since it does.
{- I probably have an item -} data Probably a = Chance a Int
instance Functor Probably where fmap f (Chance x n) = Chance (f x) (n ‘div‘ 2)
Fusion Law: fmap f. fmap g = fmap (f. g)
Reaching into a collection and altering twice is the same as reaching in and altering once.
This ensures that “alterations don’t needlessly mess with collection structure”; e.g., the following is not a functor since it does.
import Prelude hiding (Left, Right)
{- I have an item in my left or my right pocket -} data Pocket a = Left a | Right a
instance Functor Pocket where fmap f (Left x) = Right (f x) fmap f (Right x) = Left (f x)
It is important to note that functors model well-behaved container-like types, but of- course the types do not actually need to contain anything at all! E.g., the following is a valid functor.
{- “I totally have an α-value, it’s either here or there.” Lies! -} data Liar α = OverHere Int | OverThere Int
instance Functor Liar where fmap f (OverHere n) = OverHere n fmap f (OverThere n) = OverThere n
Notice that if we altered n, say by dividing it by two, then we break the identity law; and if we swap the constructors, then we break the fusion law. Super neat stuff!
In general, functors take something boring and generally furnish it with ‘coherent’ struc- ture, but there is not necessarily an α ‘inside’ f α. E.g., f α = ( → α) has as values “recipes for forming an α-value”, but unless executed, there is no α-value.
fmap f xs ≈ for each element x in the ‘collection’ xs, yield f x. Haskell can usually derive functor instances since they are unique: Only one possible definition of fmap will work. Reading the functor axioms left-to-right, they can be seen as optimisation laws that make a program faster by reducing work. The two laws together say fmap distributes over composition: fmap (f 1. f 2. · · ·. fn) = fmap f 1. · · ·. fmap fn for n ≥ 0.
Naturality Theorems: If p : : f a → g a for some functors f and g, then fmap f. p = p. fmap f for any function f.
Hence, any generic property p : : f α → is invariant over fmaps: p(fmap f xs) = p xs. E.g., the length of a list does not change even when an fmap is applied.
Functor Examples
Let f 1 , f 2 be functors and be a given type.
Type Former f α f <$> x Identity α f <$> x = f x Constant f <$> x = x List [α] f <$> [x 0 , ..., xn] = [f x 0 , ..., f xn] Either Either α f <$> x = right f Product (f 1 α, f 2 α) f <$> (x, y) = (f <$> x, f <$> y) Composition f 1 (f 2 α) f <$> x = (fmap f) <$> x Sum Either (f 1 α) (f 2 α) f <$> ea = f +++ f Writer (, α) f <$> (e, x) = (e, f x) Reader → α f <$> g = f. g State → (, α) f <$> g = second f. g
Notice that writer is the product of the constant and the identity functors.
Unlike reader, the type former f α = α → is not a functor since there is no way to implement fmap. In contrast, f α = (α → , α) does have an implementation of fmap, but it is not lawful.
Applicative
Applicatives are collection-like types that can apply collections of functions to collections of elements.
In particular, applicatives can fmap over multiple arguments; e.g., if we try to add Just 2 and Just 3, we find (+) <$> Just 2 :: Maybe (Int → Int) and this is not a function and so cannot be applied further to Just 3 to get Just 5. We have both the function and the value wrapped up, so we need a way to apply the former to the latter. The answer is (+) <$> Just 2 <*> Just 3.
class Functor f => Applicative f where pure :: a -> f a (<*>) :: f (a -> b) -> f a -> f b {- “apply” -}
{- Apply associates to the left: p <> q <> r = (p <> q) <> r) -}
The method pure lets us inject values, to make ‘singleton collections’.
Functors transform values inside collections; applicatives can additionally combine values inside collections. Exercise: If α is a monoid, then so too is f α for any applicative f.
The applicative axioms ensure that apply behaves like usual functional application:
Identity: pure id <> x = x —c.f., id x = x Homomorphism: pure f <> pure x = pure (f x) —it really is function appli- cation on pure values! ◦ Applying a non-effectful function to a non-effectful argument in an effectful context is the same as just applying the function to the argument and then injecting the result into the content. Interchange: p <> pure x = pure ($ x) <> p —c.f., f x = ($ x) f ◦ Functions f take x as input ≈ Values x project functions f to particular values
◦ When there is only one effectful component, then it does not matter whether we evaluate the function first or the argument first, there will still only be one effect. ◦ Indeed, this is equivalent to the law: pure f <> q = pure (flip ($)) <> q <> pure f. Composition: pure (.) <> p <> q <> r = p <> (q <> r) —c.f., (f. g). h = f. (g. h).
If we view f α as an “effectful computation on α”, then the above laws ensure pure cre- ates an “effect free” context. E.g., if f α = [α] is considered “nondeterminstic α-values”, then pure just treats usual α-values as nondeterminstic but with no ambiguity, and fs <> xs reads “if we nondeterminsticly have a choice f from fs, and we nondetermin- sticly an x from xs, then we nondeterminsticly obtain f x.” More concretely, if I’m given randomly addition or multiplication along with the argument 3 and another argument that could be 2, 4, or 6, then the result would be obtained by considering all possible combinations: [(+), ()] <> pure 3 <> [2, 4, 6] = [5,7,9,6,12,18]. The name “<*>” is suggestive of this ‘cartesian product’ nature.
Given a definition of apply, the definition of pure may be obtained by unfolding the identity axiom.
Using these laws, we regain the original fmap —since fmap’s are unique in Haskell— thereby further cementing that applicatives model “collections that can be functionally applied”: f <$> x = pure f <*> x. ( Hence, every applicative is a functor whether we like it or not. ) The identity applicative law is then just the identity law of functor. The homomorphism law now becomes: pure. f = fmap f. pure. ◦ This is the “naturality law” for pure.
The laws may be interpreted as left-to-right rewrite rules and so are a procedure for trans- forming any applicative expression into the canonical form of “a pure function applied to effectful arguments”: pure f <> x 1 <> · · · <*> xn. In this way, one can compute in-parallel the, necessarily independent, xi then combine them together.
Notice that the canonical form generalises fmap to n-arguments: Given f : : α 1 → · · · → αn → β and xi : : f αi, we obtain an (f β)-value. The case of n = 2 is called liftA2, n = 1 is just fmap, and for n = 0 we have pure!
Notice that lift2A is essentially the cartesian product in the setting of lists, or (<&>) below —c.f., sequenceA :: Applicative f ⇒ [f a] → f [a].
(<&>) :: f a → f b → f (a, b) {- Not a standard name! -} (<&>) = liftA2 (,) -- i.e., p <&> q = (,) <$> p <*> q
This is a pairing operation with properties of (,) mirrored at the applicative level:
{- Pure Pairing -} pure x <&> pure y = pure (x, y) {- Naturality -} (f &&& g) <$> (u <&> v) = (f <$> u) <&> (g <&> v)
{- Left Projection -} fst <$> (u <&> pure ()) = u {- Right Projection -} snd <$> (pure () <&> v) = v {- Associtivity -} assocl <$> (u <&> (v <&> w)) = (u <&> v) <&> w
The final three laws above suffice to prove the original applicative axioms, and so we may define p <*> q = uncurry ($) <$> (p <&> q).
Do-Notation Laws: Here are some desirable usability properties of do-notation.
[RightIdentity] do {B; x ← p; pure x} = do {B; p} [LeftIdentity ] do {B; x ← pure e; C; r} = do {B; C[x := e]; r[x := e]} [Associtivity ] do {B; x ← do {C; p}; D; r} = do {B; C; x ← p; D; r}
Here, B, C, D range over sequences of commands and C[x := e] means the sequence C with all free occruences of x replaced by e.
Associtivity gives us a nice way to ‘inline’ other calls. The LeftIdentity law, read right-to-left, lets us “locally give a name” to the possibly complex expression e.
If pure forms a singleton collection, then LeftIdentity is a “one-point rule”: We consider all x ← pure e, but there is only one such x, namely e!
In the applicative case, where the clauses are independent, we can prove, say, RightIdentity using the identity law for applicatives —which says essentially do {x <- p; pure x} = p— then apply induction on the length of B.
What axioms are needed for the monad case to prove the do-notation laws?
Monad Laws
Here is the definition of the monad typeclass.
class Applicative m => Monad (m :: * -> *) where (>>=) :: m a -> (a -> m b) -> m b
(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c f <=< g = join. fmap f. g
Where’s join!? Historically, monads entered Haskell first with interface (»=), return; later it was realised that return = pure and the relationship with applicative was ce- mented.
‘Bind’ (»=) is definable from join by ma »= f = join (fmap f ma), and, for this reason, bind is known as “flat map” or “concat map” in particular instances. For instance, the second definition of do-notation could be expressed:
(2M’) do {x ← p; C; r} = p >>= q where q x = do {C; r}
Conversely, join ps = do {p ← ps; p} = ps »= id. Likewise, with (2M’), note how (<>) can be defined directly in-terms of (»=) —c.f., mf <> mx = do {f ← mf; x ← mx; return (f x)}.
Since fmap f p = do {x ← p; return (f x)} = p »= return. f, in the past monad did not even have functor as a superclass —c.f., liftM.
The properties of »=, return that prove the desired do-notation laws are:
[LeftIdentity ] return a >>= f ≡ f a [RightIdentity] m >>= return ≡ m [Associtivity ] (m >>= f) >>= g ≡ m >>= (\x -> f x >>= g) i.e., (m >>= (\x -> f x)) >>= g = m >>= (\x -> f x >>= g)
Equivalently, show the ‘fish’ (<=<) is associative with identity being pure —c.f., monoids!
It is pretty awesome that (»=), return give us a functor, an applicative, and (depen- dent) do-notation! Why? Because bind does both the work of fmap and join. Thus, pure, fmap, join suffice to characterise a monad. Join determines how a monad behaves!
The monad laws can be expressed in terms of join directly:
[Associativity] join. fmap join = join. join {- The only two ways to get from “m (m (m α))” to “m α” are the same. -}
[Identity Laws] join. fmap pure = join. pure = id {- Wrapping up “m α” gives an “m (m α)” which flattens to the original element. -}
Then, notice that the (free) naturality of join is:
join. fmap (fmap f) = fmap f. join : : m (m α) → m β
Again, note that join doesn’t merely flatten a monad value, but rather performs the necessary logic that determines how the monad behaves.
E.g., suppose m α = → (, α) is the type of α-values that can be configured accord- ing to a fixed environment type , along with the possibly updated configuration —i.e., functions → (, α). Then any a : → (, → (, α)) in m (m α) can be consid- ered an element of m α if we propagate the environment configuration through the outer layer to obtain a new configuration for the inner layer: λ e → let (e’, a’) = a e in a’ e’. The join dictates how a configuration is modified then passed along: We have two actions, a and a’, and join has sequenced them by pushing the environment through the first thereby modifying it then pushing it through the second.
Monad Examples
Let f 1 , f 2 be functors and let a type. Applicative m α join :: m (m α) → m α Identity α λ x → x Constant λ x → x —Shucks! Not a monad! List [α] λ xss → foldr (++) [] xss Either Either α Exercise ˆ_ˆ Composition f 1 (f 2 α) Nope! Not a monad! Product (f 1 α, f 2 α) λ p → (fst <$> p, snd <$> p) Writer (, α) λ (e, (e’, a)) → (e <> e’, a) Reader → α λ ra → λ e → ra e e State → (, α) λ ra → λ e → let (e’, a) = ra e in a e’
In writer, we need to be a monoid. Notice how, in writer, join merges the outer context with the inner context: Se- quential writes are mappended together! If pure forms ‘singleton containers’ then join flattens containers of containers into a single container.
Excluding the trivial monoid, the constant functor is not a monad: It fails the monad identity laws for join. Similarly, f α = Maybe (α, α) is an applicative but not a monad —since there is no lawful definition of join. Hence, applicatives are strictly more gener- ally than monads.
Running Example —A Simple Arithmetic Language
Let’s start with a weak language:
data Term = Int Int | Div Term Term deriving Show
thirteen = Int 1729 ‘Div‘ (Int 133 ‘Div‘ Int 1) boom = Int 1729 ‘Div‘ (Int 12 ‘Div‘ Int 0)
eval 0 :: Term -> Int eval 0 (Int n) = n eval 0 (n ‘Div‘ d) = let top = eval 0 n bottom = eval 0 d in top ‘div‘ bottom
How do we accomodate safe division by zero? Print to the user what’s happening at each step of the calcuation? Have terms that access ‘global’ variables? Have terms that can store named expressions then access them later?
We’ll make such languages and their eval’s will be nearly just as simple as this one (!) but accomodate these other issues.
Maybe —Possibly Failing Computations
Safe evaluator: No division errors.
eval 1 :: Term -> Maybe Int eval 1 (Int n) = pure n eval 1 (n ‘Div‘ d) = do t <- eval 1 n b <- eval 1 d if b == 0 then Nothing else pure (t ‘div‘ b)
Exercise: Rewrite evali without do-notation and you’ll end-up with nested case analysis leading into a straicase of code that runs right off the page.
Applicative is enough for eval 1 , eval 2 , eval 3 , but eval 4 needs Monad.
Writer —Logging Information as we Compute
Use a pair type W α to keep track of an environment and a value α.
data Writer α = W α deriving Show
write :: -> Writer () write e = W e ()
instance Functor (Writer ) where fmap f (W e a) = W e (f a)
Aggregate, merge, environments using their monoidal operation.
instance Monoid => Applicative (Writer ) where pure a = W mempty a (W e f) <*> (W d a) = W (e <> d) (f a)
instance Monoid => Monad (Writer ) where (>>=) = \ ma f -> join (pure f <*> ma) where join (W e (W d a)) = W (e <> d) a
An evaluator that prints to the user what’s going on.
eval 2 :: Term -> Writer String Int eval 2 it@(Int n) = W ("\n Evaluating: " ++ show it) n eval 2 it@(n ‘Div‘ d) = do write $ "\n Evaluating: " ++ show it t <- eval 2 n b <- eval 2 d pure $ (t ‘div‘ b)
-- Try this! With “boom”, we get to see up to the boint of the error ^_^ -- let W e x = eval 2 thirteen in putStrLn e
Reader —Accessing ‘Global, read-only, data’
Use a function type → α to get α-values that ‘reads’ from a configuration environment .
data Reader α = R {run :: -> α}
instance Functor (Reader ) where fmap f (R g) = R $ f. g
instance Applicative (Reader ) where pure a = R $ const a (R f) <*> (R g) = R $ \e -> f e (g e) {- “S” combinator -}
instance Monad (Reader ) where ma >>= f = join (pure f <*> ma) where join (R rf) = R $ \e -> run (rf e) e
A language with access to global variables; uninitialised variables are 0 by default.
data Term = Int Int | Div Term Term | Var String deriving Show
type GlobalVars = [(String, Int)]
valuefrom :: String -> GlobalVars -> Int valuefrom x gvs = maybe 0 id $ lookup x gvs
eval 3 :: Term -> Reader GlobalVars Int eval 3 (Int x) = pure x eval 3 (Var x) = R $ \e -> x ‘valuefrom‘ e eval 3 (n ‘Div‘ d) = do t <- eval 3 n b <- eval 3 d pure (t ‘div‘ b)
state = [("x", 1729), ("y", 133)] :: GlobalVars thirteen = Var "x" ‘Div‘ (Var "y" ‘Div‘ Int 1) -- run (eval 3 thirteen) state