Guest User

Untitled

a guest
Sep 18th, 2019
91
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # lambda interpreter example.
  2.  
  3. # Values: Num, Fun & Wrong.
  4. # Terms: Cons, Var, Lam, App & Add.
  5.  
  6. class Num:
  7. def __init__(self, v):
  8. self.v = v
  9. def __str__(self):
  10. return str(self.v)
  11.  
  12. class Fun:
  13. def __init__(self, f):
  14. self.f = f
  15. def __call__(self, *args, **kargs):
  16. return self.f(*args, **kargs)
  17. def __str__(self):
  18. return 'function'
  19.  
  20. class Wrong:
  21. def __str__(self):
  22. return 'Wrong'
  23.  
  24. def add(v1, v2):
  25. return Num(v1.v + v2.v)
  26.  
  27. def apply(v1, v2):
  28. return v1(v2)
  29.  
  30. class Cons:
  31. def __init__(self, v):
  32. self.v = int(v)
  33. def interp(self, env):
  34. return Num(self.v)
  35.  
  36. class Var:
  37. def __init__(self, x):
  38. self.x = x
  39. def interp(self, env):
  40. return env[self.x]
  41.  
  42. class Lam:
  43. def __init__(self, arg, body):
  44. self.arg = arg
  45. self.body = body
  46. def interp(self, env):
  47. def f(v):
  48. env2 = env.copy()
  49. env2[self.arg] = v
  50. return self.body.interp(env2)
  51. return Fun(f)
  52.  
  53. class App:
  54. def __init__(self, fun, param):
  55. self.fun = fun
  56. self.param = param
  57. def interp(self, env):
  58. return apply(self.fun.interp(env),
  59. self.param.interp(env))
  60.  
  61. class Add:
  62. def __init__(self, a, b):
  63. self.a = a
  64. self.b = b
  65. def interp(self, env):
  66. return add(self.a.interp(env), self.b.interp(env))
  67.  
  68.  
  69. expr = App( Lam('x', Add(Var('x'), Var('x'))),
  70. Add(Cons(10), Cons(11)) )
  71.  
  72. print(expr.interp({}))
RAW Paste Data