Skip to content

Instantly share code, notes, and snippets.

@Cedev
Last active August 29, 2015 14:16
Show Gist options
  • Save Cedev/087c3e50ecc53e0f04e9 to your computer and use it in GitHub Desktop.
Save Cedev/087c3e50ecc53e0f04e9 to your computer and use it in GitHub Desktop.
import Control.Applicative
import Data.List
import Data.Maybe
data Term = Var Int | Lam Int Term | App Term Term deriving (Show)
data BTerm = BVar Int | BLam BTerm | BApp BTerm BTerm deriving (Show) -- BVar 0 refers to the closest lambda
lam2db :: Term -> Maybe BTerm
lam2db = go []
where
go xs (Var x) = BVar <$> elemIndex x xs -- elemIndex is exploiting 0 being the first list index
go xs (Lam x exp) = BLam <$> go (x:xs) exp
go xs (App exp1 exp2) = BApp <$> go xs exp1 <*> go xs exp2
-- | Safe version of `!!`
(!?) :: [a] -> Int -> Maybe a
xs !? n = listToMaybe (drop n xs)
db2lam :: BTerm -> Maybe Term
db2lam = go [15..] []
where
go names xs (BVar x) = Var <$> xs !? x -- exploiting 0 being the first list index.
go (x:names) xs (BLam exp) = Lam x <$> go names (x:xs) exp
go names xs (BApp exp1 exp2) = App <$> go names xs exp1 <*> go names xs exp2
main = do
let b = BLam (BLam (BVar 1))
print b
let l = db2lam b
print l
let b' = l >>= lam2db
print b'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment