Implementing Alpha-Equivalence in haskell

2019-07-19 01:11发布

I want to define Alpha-Equivalence using this data definition

type Sym = Char
data Exp = Var Sym | App Term Exp | Lam Sym Exp 
deriving (Eq, Read, Show)

What is the best way to do this?

1条回答
你好瞎i
2楼-- · 2019-07-19 01:18

One way is to convert names to De Bruijn indices, where e.g. 0 refers to the variable bound by the innermost enclosing lambda, 1 the next enclosing lambda, and so on. So instead of absolute names, you use relative indices, giving you alpha-equivalence and capture-avoiding substitution for free:

type Sym = Char
data Exp = Var Sym | App Exp Exp | Lam Sym Exp
  deriving (Eq, Read, Show)

type Ind = Int
data Exp' = Var' Ind | App' Exp' Exp' | Lam' Exp'
  deriving (Eq, Read, Show)

To do the conversion, you just keep an environment of the names in scope:

db :: Exp -> Exp'
db = go []
  where

    -- If we see a variable, we look up its index in the environment.
    go env (Var sym) = case findIndex (== sym) env of
      Just ind -> Var' ind
      Nothing -> error "unbound variable"

    -- If we see a lambda, we add its variable to the environment.
    go env (Lam sym exp) = Lam' (go (sym : env) exp)

    -- The other cases are straightforward.
    go env (App e1 e2) = App' (go env e1) (go env e2)

Now, alpha equivalence is simple:

alphaEq x y = db x == db y
-- or:
alphaEq = (==) `on` db

Examples:

-- λx.x ~ λy.y
Lam 'x' (Var 'x') `alphaEq` Lam 'y' (Var 'y')  ==  True

-- λx.λy.λz.xz(yz)
s1 = Lam 'x' $ Lam 'y' $ Lam 'z'
  $ Var 'x' `App` Var 'z' `App` (Var 'y' `App` Var 'z')

-- λa.λb.λc.ac(bc)
s2 = Lam 'a' $ Lam 'b' $ Lam 'c'
  $ Var 'a' `App` Var 'c' `App` (Var 'b' `App` Var 'c')

-- λa.λb.λc.ab(ac)
s3 = Lam 'a' $ Lam 'b' $ Lam 'c'
  $ Var 'a' `App` Var 'b' `App` (Var 'a' `App` Var 'c')

s1 `alphaEq` s2  ==  True
s1 `alphaEq` s3  ==  False
查看更多
登录 后发表回答