什么是枚举lambda术语的算法?

时间:2014-01-09 05:54:44

标签: algorithm functional-programming lambda-calculus

什么算法会按长度顺序枚举lambda演算的表达式?例如,(λx.x), (λx.(x x)), (λx.(λy.x))等等?

2 个答案:

答案 0 :(得分:2)

作为长度,我会在(无类型)lambda表达式的BNF中选择T - 扩展(“深度”)的数量:

V ::= x | y
T ::= V    | 
      λV.T |
      (T T)

在python中,你可以按照上面给定变量的生成规则和给定的深度定义一个生成器,如下所示:

def lBNF(vars, depth):
  if depth == 1:
    for var in vars:
      yield var
  elif depth > 1:
    for var in vars:
      for lTerm in lBNF(vars,depth-1):
        yield 'l%s.%s' % (var,lTerm)
    for i in range(1,depth):
      for lTerm1 in lBNF(vars,i):
        for lTerm2 in lBNF(vars,depth-i):
          yield '(%s %s)' % (lTerm1,lTerm2)

现在,您可以枚举/达到给定深度的lambda术语:

vars = ['x','y']
for i in range(1,5):
  for lTerm in lBNF(vars,i):
    print lTerm

答案 1 :(得分:1)

请参阅第5页的https://arxiv.org/abs/1210.2610。以下是一些示例代码:

from itertools import chain, count
from functools import lru_cache

@lru_cache(maxsize=None)
def terms(size, level=0):
    if size == 0:
        return tuple(range(level))
    else:
        abstractions = (
            ('abs', term)
            for term in terms(size - 1, level + 1)
        )
        applications = (
            ('app', term1, term2)
            for i in range(size)
            for term1 in terms(i, level)
            for term2 in terms(size - 1 - i, level)
        )
        return tuple(chain(abstractions, applications))

def string(term):
    if isinstance(term, tuple):
        if term[0] == 'abs':
            return '(λ {})'.format(string(term[1]))
        elif term[0] == 'app':
            return '({} {})'.format(string(term[1]), string(term[2]))
    else:
        return term

for size in count():
    print('{} terms of size {}'.format(len(terms(size)), size))
    for term in terms(size):
        pass # input(string(term))

此输出

0 terms of size 0
1 terms of size 1
3 terms of size 2
14 terms of size 3
82 terms of size 4
579 terms of size 5
4741 terms of size 6
43977 terms of size 7
454283 terms of size 8

依此类推(即this sequence)。