Gyh's Braindump

scheme

tags
Programming Languages

Expression

  • prefix notation
  • allow nesting
(+ (* 3
      (+ (* 2 4)
         (+ 3 5)))
   (+ (- 10 7)
      6))

Naming

  • use define
(define size 2)
(* 5 size)

Procedure

(define (<name> <formal parameters>)
  <body>)

Block Structure

Procedures can have internal definitions that are local to them. Internal definitions must come first in the procedure body.

Conditions

Cond

  • evaluate <p> until one is true, if all false, cond return undefined value
  • in Scheme, #f means false, any other value is true, however, we use #t to denote it for convenience
  • <e1> can be a sequence of expressions
(cond (<p1> <e1>)
      (<p2> <e2>)
      ...
      (<pn> <en>))
      <(else <en>)>)
example:
(define (abs x)
  (cond ((> x 0) x)
        ((= x 0) 0)
        ((< x 0) -x)))

If

consequent and alternative must be single expression

(if <predicate> <consequent> <alternative>)

Logical operations

and
(and <e1> ... <en>), SPECIAL FORMS evaluate from left to right, stop when one is false
or
(or <e1> ... <en>), SPECIAL FORMS stop when one is true, PROCEDURE
not
(not <e>)

Pair (compound-data primitive)

cons

stands for “construct”

car

stands for “Contents of Address part of Register”

cdr

  • pronounced “could-er”
  • stands for “Contents of Decrement part of Register”

example

(define x (cons 1 2))
(define y (cons 3 4))
(define z (cons x y))
(car (car z))
; 1
(car (cdr z))
3

List

  • (list <a1> <a2> ... <an>) equals to nesed cons.
  • use null? to test whether its arg is the empty list: (null? items)
(define one-through-four (list 1 2 3 4))
one-through-four
(1 2 3 4)
(car one-through-four)
1
(cdr one-through-four)
(2 3 4)
(car (cdr one-through-four))
2
(cons 10 one-through-four)
(10 1 2 3 4)
(cons 5 one-through-four)
(5 1 2 3 4)

Links to this note