25.10.2015 Views

Write You a Haskell Stephen Diehl

1kEcQTb

1kEcQTb

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

[x/e ′ ]x = e ′<br />

[x/e ′ ]y = y (y ≠ x)<br />

[x/e ′ ](e 1 e 2 ) = ([x/e ′ ] e 1 )([x/e ′ ]e 2 )<br />

[x/e ′ ](λy.e 1 ) = λy.[x/e ′ ]e y ≠ x, x /∈ fv(e ′ )<br />

And likewise, substitutions can be applied element wise over the typing environment.<br />

[t/s]Γ = {y : [t/s]σ | y : σ ∈ Γ}<br />

Our implementation of a substitution in <strong>Haskell</strong> is simply a Map from type variables to types.<br />

type Subst = Map.Map TVar Type<br />

Composition of substitutions ( s 1 ◦ s 2 , s1 ‘compose‘ s2 ) can be encoded simply as operations over<br />

the underlying map. Importantly note that in our implementation we have chosen the substitution to<br />

be left-biased, it is up to the implementation of the inference algorithm to ensure that clashes do not<br />

occur between substitutions.<br />

nullSubst :: Subst<br />

nullSubst = Map.empty<br />

compose :: Subst -> Subst -> Subst<br />

s1 ‘compose‘ s2 = Map.map (apply s1) s2 ‘Map.union‘ s1<br />

e implementation in <strong>Haskell</strong> is via a series of implementations of a Substitutable typeclass which<br />

exposes the apply which applies the substitution given over the structure of the type replacing type<br />

variables as specified.<br />

class Substitutable a where<br />

apply :: Subst -> a -> a<br />

ftv :: a -> Set.Set TVar<br />

instance Substitutable Type where<br />

apply _ (TCon a) = TCon a<br />

apply s t@(TVar a) = Map.findWithDefault t a s<br />

apply s (t1 ‘TArr‘ t2) = apply s t1 ‘TArr‘ apply s t2<br />

ftv TCon{}<br />

= Set.empty<br />

ftv (TVar a) = Set.singleton a<br />

ftv (t1 ‘TArr‘ t2) = ftv t1 ‘Set.union‘ ftv t2<br />

instance Substitutable Scheme where<br />

apply s (Forall as t) = Forall as $ apply s’ t<br />

84

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!