Implementing Alpha-Equivalence in haskell

瘦欲@ 提交于 2019-12-11 02:43:15

问题


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:


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


来源:https://stackoverflow.com/questions/40316605/implementing-alpha-equivalence-in-haskell

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!