Programming Paradigms CSI2120 - Winter 2019: Jochen Lang EECS, University of Ottawa Canada
Programming Paradigms CSI2120 - Winter 2019: Jochen Lang EECS, University of Ottawa Canada
Paradigms CSI2120
– Winter 2019
Jochen Lang
EECS, University of Ottawa
Canada
Scheme: Functional Programming
• let
– to define a list of local variables for a list of expressions
– each variable name is bound with a value
– let returns the result of the last expression
• but evaluates all expressions from left to right
(let ((a 2) (b 3)) ; local variables a and b
(+ a b)) ; expression where the
; variables are bound
=> 5
a
=> Unbound variable: a
b
=> Unbound variable: b
(let ((a 3)
(b 4)
(square (lambda (x) (* x x)))
(plus +)) ; end of definitions
; applied to
(sqrt (plus (square a) (square b))))
=> 5
(define seconds
(lambda (h m s)
(let ((sh (* 60 (* 60 h)))
(sm (* 60 m)))
(+ s (+ sh sm)))))
=> seconds
(seconds 1 5 3)
=> 3903
• letrec
– permits the recursive definitions of functions
– letrec is similar let* but all the bindings are within the
scope of the corresponding variable
• Example: Local definition of factorial
(letrec ((fact (lambda (n)
(if (= n 1)
1
(* n (fact (- n 1)))))))
(fact 5))
=> 120
(define num-calls 0)
=> num-calls
(define kons
(lambda (x y)
(set! num-calls (+ num-calls 1))
(cons x y)))
=> kons
(kons 3 5)
=> (3 . 5)
(display num-calls)
1
• Character constants:
#\a #\A #\( #\space #\newline
• Predicats:
– Mostly obvious
(char? obj) tests whether obj is a character.
(char-alphabetic? char)
(char-numeric? char)
(char-whitespace? char)
(char-upper-case? char)
(char-lower-case? char)
• Character to ascii
(char->integer #\a)
97
• Character to ascii and back
(integer->char (1+ (char->integer #\a)))
#\b
(string-length "Hello")
=> 5
(string->list "Hello")
=> (#\H #\e #\l #\l #\o)
(substring "computer" 3 6)
=> "put"