25.10.2015 Views

Write You a Haskell Stephen Diehl

1kEcQTb

1kEcQTb

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

test :: Integer<br />

test = eval fact 10<br />

main :: IO ()<br />

main = print test<br />

Several caveats must be taken when working with HOAS. First of all, it takes more work to transform<br />

expressions in this form since in order to work with the expression we would need to reach under the<br />

lambda binder of a <strong>Haskell</strong> function itself. Since all the machinery is wrapped up inside of <strong>Haskell</strong>’s<br />

implementation even simple operations like pretty printing and writing transformation passes can be<br />

more difficult. is form is a good form for evaluation, but not for transformation.<br />

Parametric Higher Order Abstract Syntax (PHOAS)<br />

A slightly different form of HOAS called PHOAS uses a lambda representation parameterized over the<br />

binder type under an existential type.<br />

{-# LANGUAGE RankNTypes #-}<br />

data ExprP a<br />

= VarP a<br />

| AppP (ExprP a) (ExprP a)<br />

| LamP (a -> ExprP a)<br />

| LitP Integer<br />

newtype Expr = Expr { unExpr :: forall a . ExprP a }<br />

e lambda in our language is simply a lambda within <strong>Haskell</strong>. As an example, the usual SK combinators<br />

would be written as follows:<br />

-- i x = x<br />

i :: ExprP a<br />

i = LamP (\a -> VarP a)<br />

-- k x y = x<br />

k :: ExprP a<br />

k = LamP (\x -> LamP (\y -> VarP x))<br />

-- s f g x = f x (g x)<br />

s :: ExprP a<br />

s =<br />

LamP (\f -><br />

LamP (\g -><br />

LamP (\x -><br />

74

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

Saved successfully!

Ooh no, something went wrong!