Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Syntax Name Kind Description<br />
(,) Pair * -> * -> * 2-Tuple<br />
() Unit * Unit type<br />
(->) Arrow * -> * -> * Arrow type<br />
Bool Bool * Boolean<br />
IO IO * -> * IO Monad<br />
Traversals<br />
Bottom-up traversals and rewrites in a monadic context are so that common that we’d like to automate<br />
this process so that we don’t have duplicate the same logic across all our code. So we’ll write several<br />
generic traversal functions.<br />
descendM :: (Monad m, Applicative m) => (Expr -> m Expr) -> Expr -> m Expr<br />
descendM f e = case e of<br />
EApp a b -> EApp descendM f a descendM f b<br />
EVar a -> EVar pure a<br />
ELam a b -> ELam pure a descendM f b<br />
ELit n -> ELit pure n<br />
ELet n a b -> ELet pure n descendM f a descendM f b<br />
EIf a b c -> EIf descendM f a descendM f b descendM f c<br />
ECase a xs -> ECase f a traverse (descendCaseM f) xs<br />
EAnn a t -> EAnn descendM f a pure t<br />
EFail -> pure EFail<br />
descendCaseM :: (Monad m, Applicative m) => (Expr -> m Expr) -> Match -> m Match<br />
descendCaseM f e = case e of<br />
Match ps a -> Match pure ps descendM f a<br />
e case where the monad is Identity simply corresponds to a pure expression rewrite.<br />
descend :: (Expr -> Expr) -> Expr -> Expr<br />
descend f ex = runIdentity (descendM (return . f) ex)<br />
For example a transformation for use in this framework of traversals might just use pattern matching<br />
to match specific syntactic structure and rewrite it or simply yield the input and traverse to the next<br />
element in the bottom-up traversal.<br />
A pure trnasformation that rewrites all variables named “a” to “b” might be written concisely as the<br />
following higher order function.<br />
transform :: Expr -> Expr<br />
transform = descend f<br />
125