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.

e 1 → e 2<br />

succ e 1 → succ e 2<br />

e 1 → e 2<br />

pred e 1 → pred e 2<br />

pred 0 → 0<br />

pred (succ n) → n<br />

e 1 → e 2<br />

iszero e 1 → iszero e 2<br />

iszero 0 → true<br />

iszero (succ n) → false<br />

if True then e 2 else e 3 → e 2<br />

if False then e 2 else e 3 → e 3<br />

(E-Succ)<br />

(E-Pred)<br />

(E-PredZero)<br />

(E-PredSucc)<br />

(E-IsZero)<br />

(E-IsZeroZero)<br />

(E-IsZeroSucc)<br />

(E-IfTrue)<br />

(E-IfFalse)<br />

e evaluation logic for our interpreter simply reduced an expression by the predefined evaluation rules<br />

until either it reached a normal form ( a value ) or got stuck.<br />

nf :: Expr -> Expr<br />

nf t = fromMaybe t (nf eval1 t)<br />

eval :: Expr -> Maybe Expr<br />

eval t = case isVal (nf t) of<br />

True -> Just (nf t)<br />

False -> Nothing -- term is ”stuck”<br />

Values in our language are defined to be literal numbers or booleans.<br />

isVal :: Expr -> Bool<br />

isVal Tr = True<br />

isVal Fl = True<br />

isVal t | isNum t = True<br />

isVal _ = False<br />

Written in applicative form there is a noticeable correspondence between each of the evaluation rules<br />

and our evaluation logic.<br />

-- Evaluate a single step.<br />

eval1 :: Expr -> Maybe Expr<br />

58

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

Saved successfully!

Ooh no, something went wrong!