Advertisement
Guest User

Untitled

a guest
Nov 26th, 2015
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. The following is a collection of notes generated while learning CHICKEN Scheme.
  2.  
  3. ## Syntax
  4. Function definition using `defun`:
  5. ```lisp
  6. (define (my-name arg1 arg2)
  7. (body...))
  8. ```
  9.  
  10. Functions that return true (`#t`) or false (`#f`) are called _predicates_:
  11. ```lisp
  12. (zero? 0) ; #t
  13. ```
  14. Some predicates are `eq?`, `equal?`, `zero?` and `number?`.
  15.  
  16. To control the flow of evaluation, _conditionals_, use `cond`.
  17. ```lisp
  18. (cond
  19. (predicate body) ; clause 1
  20. (predicate body)) ; clause 2
  21. ```
  22. `cond` evaluates the predicate of the first clause, if it's truthy (everything but #f is considered true), it evaluates body
  23. and ignores other clauses. Otherwise, it moves onto the second clause and repeats. It's good to always catch the last statement
  24. with #t.
  25.  
  26. Factorial, could be written as follows:
  27. ```lisp
  28. (cond ((zero? n) 1)
  29. (#t (* n (fact (- n 1))))))
  30. ```
  31. `cond` returns the value of the evaluated block. A shortcut is using `else`
  32. ```lisp
  33. (cond ((zero? n) 1)
  34. (else (* n (fact (- n 1))))))
  35. ```
  36.  
  37. Yet another way is using `if`
  38. ```lisp
  39. ;(if condition consequent alternative)
  40. (if #t 1 2) ; => 1
  41. ```
  42.  
  43. ## Loops and recursion
  44. A program that ‘‘does not do anything’’after calling itself is called a tail
  45. recursive program. Fact2 is a tail-recursive program, while the original
  46. fact program is not, because it applies * to the value returned by the
  47. recursive call:
  48.  
  49. ```lisp
  50. (* n (fact (- n 1)))
  51. ; ^^^--- this is done after the return of fact
  52. ```
  53.  
  54. Wrapping a tail-recursive function is common.
  55. ```lisp
  56. (define (fact n)
  57. (fact2 n 1))
  58. ```
  59.  
  60. There's a shortcut for that:
  61. ```lisp
  62. (define (fact n)
  63. (letrec
  64. ((fact2
  65. (lambda (n r)
  66. (cond ((zero? n) r)
  67. (#t (fact2 (- n 1) (* n r)))))))
  68. (fact2 n 1)))
  69. ```
  70. ## Manual Reduction
  71. Lambda calculus, is basically, a process of substitution. Just reduce the values until you get a result: Eg:
  72. ```
  73. (fact 3)
  74. -> (cond ((zero? 3) 1) (#t (* 3 (fact (- 3 1)))))
  75. -> (* 3 (fact (- 3 1)))
  76. -> (* 3 (fact 2))
  77. -> (* 3 (* 2 (fact 1)))
  78. -> (* 3 (* 2 (* 1 (fact 0))))
  79. -> (* 3 (* 2 (* 1 1)))
  80. -> (* 3 (* 2 1))
  81. -> (* 3 2)
  82. => 6
  83. ```
  84. At some point the reduction normally reachesa point where the expression cannot be reduced any further.
  85. Such an expression is said to be in its normal form.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement