Software II: Principles of Programming Languages

Dr. R. M. Siegfried

Functional Languages: Scheme

If this does not answer all your questions, please go to CSC 160 - A First Course In Computer Programming - Notes index

Scheme

Expressions in Scheme

Function definitions

Conditional Expressions in Scheme

  • There are two mechanisms for writing conditional expressions in Scheme
  • cond
  • if

  • cond expressions are:
    (cond
        [(condition1) (expression1) ]
        [(condition2) (expression2) ]
        [else (cexpression3)]
       )

    cond statements: An Example

    (define (sign-check x)
      (cond
        [(> x 0) 'Positive ]
        [(< x 0) 'Negative ]
        [else 'zero ]
       )
     )

    if expressions

    if Expressions: Examples

    (define (check-sign x)
      (if (> x 0) 'Positive))

    (define (check-sign x)
      (if (> x 0) 'Positive 'Nonpositive))

    (define (check-sign x)
      (if (> x 0) 'Positive
     (if (< x 0) 'Negative 'Zero)))

    Lists in Scheme

    Using Lists in Scheme

    (define (number x)
      (cond
        [(empty? x) 0]
        [else (+ 1 (number (rest x)))]
      )
    )
    (define (average x)
      (/ (sum x) (number x)
      )
    }

    Predicates

    Using Predicates

    (define (sum x)
      (cond
        [(empty? x) 0]
        [else
         (cond
           [(number? (first x))
              (+ (first x) (sum (rest x)))]
           [else (sum(rest x))])]
      )
    )

    Sorting in Scheme

    ;; sort : list-of-numbers -> list-of-numbers
         ;; to create a list of numbers with the
         ;; same numbers as alon sorted in
         ;; descending order
         (define (sort alon)
           (cond
             [(empty? alon) empty]
             [(cons? alon) (insert (first alon)
                            (sort (rest alon)))]))

    ;; insert : number sorted-number-list -> number-
    ;;   list to create a list of numbers from n and
    ;;   alon that is sorted in descending order;
    ;;   alon is sorted
    (define (insert n alon)
      (cond
        [(empty? alon) (cons n empty)]
        [else (cond
                [(< n (first alon)) (cons n alon)]
                [else (cons (first alon)
        (insert n (rest alon)))])]))

    [Back to the Assignment Index]