![]() Typically you might represent this with instead. When you express an intermediate state as Fun (Val -> Val), it also contains an implicit Env, which is in some sense a reader monad pattern. But since any lambda reduction rule provides another term, Term should be an excellent intermediate representation. For example, you can only pretty-print the result if it's an integer, or a failure.Īs an intermediate representation of a term being evaluated. The drawback is that you can't further transform the structure hidden away in a Fun (Val -> Val) in the same way as you can with a Term you can only reduce it further using interp. And that if one were to return a value that hasn't reduced to an integer, then rather produce a Haskell function that can resume evaluation later. Theoretically it must always be, but for a practical purpose, perhaps, you've decided that integers are different from functions. The final result of interp could be a lambda. ![]() I'm a little skeptical about Fun (Val -> Val): This seems to serve two purposes: Instead of having Wrong built into the result type, you would rather want Maybe Val, or better yet, Either String Val or Either Error val, since there are multiple possible causes for failure. I wanted to give a more full answer, but I can't fully commit to it, so here are a few things: Interp (Add a b) e = add (interp a e) (interp b e)Įxpr = App (Lam "x" (Add (Var "x") (Var "x"))) (Add (Cons 10) (Cons 11)) Interp (App f t) e = apply (interp f e) (interp t e) Interp (Lam s t) e = Fun (\v -> interp t (Map.insert s v e)) interp (Var s) e = maybe Wrong id (Map.lookup s e) Interp (Var s) e = Map.findWithDefault Wrong s e - Equivalent to: I would like it to be the cleanest and most idiomatic possible.īonus question: how would you use deriving (Show) for Val, just having to define show for Fun (Val -> Val)? - Lambda calculus interpreter example.ĭata Val = Num Integer | Fun (Val -> Val) | Wrongĭata Term = Cons Integer | Var String | Lam String Term | App Term Term | Add Term Term For learning purpose, I've written a simple lambda calculus interpreter (plus 'Add').
0 Comments
Leave a Reply. |