Advertisement
Guest User

Untitled

a guest
Apr 25th, 2015
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. import Control.Applicative
  2. import Data.List
  3. import Data.Maybe
  4.  
  5. data Term = Var Int | Lam Int Term | App Term Term deriving (Show)
  6. data BTerm = BVar Int | BLam BTerm | BApp BTerm BTerm deriving (Show) -- BVar 0 refers to the closest lambda
  7.  
  8. lam2db :: Term -> Maybe BTerm
  9. lam2db = go []
  10. where
  11. go xs (Var x) = BVar <$> elemIndex x xs -- elemIndex is exploiting 0 being the first list index
  12. go xs (Lam x exp) = BLam <$> go (x:xs) exp
  13. go xs (App exp1 exp2) = BApp <$> go xs exp1 <*> go xs exp2
  14.  
  15. -- | Safe version of `!!`
  16. (!?) :: [a] -> Int -> Maybe a
  17. xs !? n = listToMaybe (drop n xs)
  18.  
  19. db2lam :: BTerm -> Maybe Term
  20. db2lam = go [15..] []
  21. where
  22. go names xs (BVar x) = Var <$> xs !? x -- exploiting 0 being the first list index.
  23. go (x:names) xs (BLam exp) = Lam x <$> go names (x:xs) exp
  24. go names xs (BApp exp1 exp2) = App <$> go names xs exp1 <*> go names xs exp2
  25.  
  26. main = do
  27. let b = BLam (BLam (BVar 1))
  28. print b
  29. let l = db2lam b
  30. print l
  31. let b' = l >>= lam2db
  32. print b'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement