Guest User

Untitled

a guest
Jul 18th, 2018
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.91 KB | None | 0 0
  1. let rec subst e x t =
  2. match e with
  3. | ID s -> if s = x then t else ID s
  4. | BOOL b -> BOOL b
  5. | ERROR s -> ERROR s
  6. | ISZERO -> ISZERO
  7. | NUM n -> NUM n
  8. | PRED -> PRED
  9. | SUCC -> SUCC
  10. | APP (e1, e2) -> APP (subst e1 x t, subst e2 x t)
  11. | IF (b, e1, e2)-> IF (subst b x t, subst e1 x t, subst e2 x t)
  12. | FUN (s, t2) -> if s = x then FUN (s, t2) else FUN (s, subst t2 x t)
  13. | REC (s, t2) -> if s = x then REC (s, subst t2 x t) else REC (s, t2) //ERROR "AT REC SUB"
  14.  
  15. //if s != x then do fun (s, subst t2 x t) else return fun (s, t2) .. same for rec
  16.  
  17. let rec interp = function
  18. | NUM n -> NUM n // Rule (1)
  19. | BOOL true -> BOOL true // Rule (2)
  20. | BOOL false -> BOOL false // Rule (2)
  21. | SUCC -> SUCC // Rule (3)
  22. | PRED -> PRED // Rule (3)
  23. | ISZERO -> ISZERO // Rule (3)
  24. | ERROR s -> ERROR s
  25. | ID s -> ERROR (sprintf "unbound identifier ID \"%A\" (stuck)" s)
  26. | FUN (s, t) -> FUN (s, t) // Rule (9)
  27. | REC (s, t) -> interp (subst t s t) // Rule (11)
  28. | IF (b, e1, e2) ->
  29. match interp b with
  30. | BOOL true -> interp e1 // Rule (4)
  31. | BOOL false -> interp e2 // Rule (5)
  32. | _ -> ERROR (sprintf "'if' statement must evaluate to a BOOL val of true or
  33. false (stuck), current value is '%A'" (interp b))
  34. | APP (e1, e2) ->
  35. match (interp e1, interp e2) with
  36. | (ERROR s, _) -> ERROR s
  37. | (_, ERROR s) -> ERROR s
  38. | (SUCC, NUM n) -> NUM (n+1) // Rule (6)
  39. | (SUCC, v) -> ERROR (sprintf "'succ' needs int argument, not '%A'" v)
  40. | (PRED, NUM n) -> if n = 0 then NUM 0 else NUM (n-1) // Rule (7)
  41. | (PRED, v) -> ERROR (sprintf "'pred' needs int argument, not '%A'" v)
  42. | (ISZERO, NUM n) -> if n = 0 then BOOL true else BOOL false // Rule (8)
  43. | (ISZERO, v) -> ERROR (sprintf "'iszero' needs int argument, not '%A'" v)
  44. | (FUN (s, t), v) -> interp (subst t s v) // Rule (10)
  45. | (_, _) -> ERROR "invalid 'app' operation"
  46.  
  47. interp (parsestr "(rec d -> fun n -> if iszero n thn 0 else succ (succ (d (pred n)))) #37")
  48.  
  49. produces -->
  50.  
  51. val it : term =
  52. FUN
  53. ("n",
  54. IF
  55. (APP (ISZERO,ID "n"),NUM 0,
  56. APP
  57. (SUCC,
  58. APP
  59. (SUCC,
  60. APP
  61. (FUN
  62. ("n",
  63. IF
  64. (APP (ISZERO,ID "n"),NUM 0,
  65. APP (SUCC,APP (SUCC,APP (ID "d",APP (PRED,ID "n")))))),
  66. APP (PRED,ID "n"))))))
Add Comment
Please, Sign In to add comment