Skip to content

Instantly share code, notes, and snippets.

@andrusha
Created May 16, 2012 19:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrusha/2713435 to your computer and use it in GitHub Desktop.
Save andrusha/2713435 to your computer and use it in GitHub Desktop.
Lambda-calculus beta-reduction algorithm
import Data.Traversable
data Term a =
Var a
| Lambda a (Term a)
| Apply (Term a) (Term a)
instance Show a => Show (Term a) where
show (Var v) = show v
show (Lambda n t) = "/" ++ (show n) ++ "." ++ (show t)
show (Apply t1 t2) = "(" ++ (show t1) ++ " " ++ (show t2) ++ ")"
--instance Traversable (Term a) where
-- traverse f (Var a) = f (Var a)
-- traverse f (Lambda n t) = f (Lambda n (traverse t))
-- traverse f (Apply t1 t2) = f (Apply (traverse t1) (traverse t2))
reduce :: Eq a => Term a -> Term a
reduce (Var v) = Var v
reduce (Lambda a t) = Lambda a (reduce t)
reduce (Apply t1 t2) = apply (reduce t1) (reduce t2)
apply :: Eq a => Term a -> Term a -> Term a
apply (Lambda param t1) t2 = reduce $ rename param t2 t1
apply t1 t2 = Apply t1 t2
fmap' :: (Term a -> Term a) -> Term a -> Term a
fmap' f (Var v) = f (Var v)
fmap' f (Lambda v t) = Lambda v (fmap' f t)
fmap' f (Apply t1 t2) = Apply (fmap' f t1) (fmap' f t2)
rename :: Eq a => a -> Term a -> Term a -> Term a
rename a t1 t2 = fmap' replace t2
where replace = \(Var x) -> if x == a then t1 else (Var x)
@mevans
Copy link

mevans commented Dec 2, 2019

Why didn't you do more???

@andrusha
Copy link
Author

andrusha commented Dec 3, 2019 via email

@mevans
Copy link

mevans commented Dec 3, 2019

Haha, thanks very much for this gist, was super helpful!

@Anupknj
Copy link

Anupknj commented Dec 4, 2019

how do you run it?
I mean function call and arguments stuff

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment