Scheme as implemented by Racket (Simple view:) Racket is a version of Scheme. (Full view:) Racket is a platform for implementing and using many languages, and Scheme is one of those that come out of the box. Racket’s version of Scheme is somewhat different from the standards, e.g., function names, some features. My slides are right for Racket, but may fail with standard Scheme. But same principles. My slides give you a taste, but there are a lot of useful things I won’t cover. 1 / 33
33
Embed
Scheme as implemented by Racket - University of Torontotrebla/CSCC24-2018-Winter/01-scheme-p1.pdf · Scheme as implemented by Racket ... Anonymous Functions/Procedures (lambda, )
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Scheme as implemented by Racket(Simple view:) Racket is a version of Scheme.
(Full view:) Racket is a platform for implementing and using manylanguages, and Scheme is one of those that come out of the box.
Racket’s version of Scheme is somewhat different from thestandards, e.g., function names, some features. My slides are rightfor Racket, but may fail with standard Scheme.
But same principles.
My slides give you a taste, but there are a lot of useful things Iwon’t cover.
I Symbols: User-defined atomic values. You think up a name,put a single-quote in front. Four examples:’Firefox ’Chrome ’Edge ’Safari
Great for tags, labels, enumerations.
Symbols are not strings. You can’t append, split, ask for thenth character. . .
2 / 33
Expressions
I Literals: Examples on the previous slide.
I Identifiers: E.g., +, my-angle/time
I Procedure/Function Applications: (proc param1 param2 ...)
proc and parameters are expressions. proc should evaluateto a procedure.
E.g., (sin (/ 0.2 2))
E.g., ((if #t sin cos) (/ 0.2 2))
I Special Forms: (keyword expr expr ...)
For definitions, conditionals, other features. . . They have theirown slides.
3 / 33
Some Boolean Operations(not expr)
(and expr expr ...)
Short-circuits.(and) gives #t.
(or expr expr ...)
Short-circuits.(or) gives #f.
(boolean? expr)
Tests whether you have a boolean value.
4 / 33
Some Number Operations+ - * / max min can take multiple operands.
quotient remainder abs sqrt sin cos tan etc.
(expt b x) means bx.(exp x) means ex.(log x) means ln x.
= < <= > >= can take multiple operands, e.g.,(> x y z) means x > y > z.
number? tests whether a value is a number.
complex?, real?, rational?, integer? test what kind of number.
number->string
string->number (has ways to indicate parse errors)
5 / 33
Some String Operations(string-length str): length.
(string-ref str k): character at position k (start from 0).
(substring str i j) like Python’s str[i:j].(substring str i) like str[i:].
(string-append str1 str2 ...): concatenation.(string-append) gives the empty string.
string=? string<? string<=? string>? string>=?
Comparisons. Can take multiple operands. There are alsocase-insensitive versions.
string? tests whether a value is a string.
6 / 33
EqualityEquality is a mess. Three kinds, each with its intention and “but”s.
I eq? Good for booleans and symbols.
Pointer equality for most aggregates, e.g., strings, lists.
Complicated rules for numbers.
Intention: Fast, just compare two machine words.
I eqv? Good for characters.
Complicated rules for numbers, and different from eq?.(Rationale: Choices in treating floating-point’s NaN andsigned zero.)
Most other types: Same as eq?.
I equal? Structural equality for most aggregates, i.e.,comparing contents.
7 / 33
DefinitionsGive cool names to cool things.
Examples:
; A constant.(define my-width/height (/ 4 3))
; A function with 1 parameter.(define (greet person)(string-append "hello " person))
; A function with 2 parameters.(define (my-log base x)(/ (log x) (log base)))
Recursion is allowed.
8 / 33
Anonymous Functions/Procedures (lambda, λ)(Terminology: “procedure” expected to be effectful, e.g., I/O;“function” expected to be effect-free. Not strictly enforced though.)
Can write a function without name; “procedure expression”.(lambda (param1 param2 ...) body)
Function definition (define (f x y) body) is short-hand for(define f (lambda (x y) body)).
May also write λ.
9 / 33
ConditionalsIf-then-else: (if test then-expr else-expr)Actually test can be non-boolean—treated as true.
Multiple conditions:
(cond[(> x y) (sin x)][(< x y) (cos y)][else 0])
If x > y then sin x; else if x < y then cos y; else 0.
Test results can be non-boolean—treated as true. Furthermoreyou can obtain and use it:
(cond[(+ 4 2) => (lambda (x) (* x x))][else 0])
This gives 36.
10 / 33
and, or As Conditionals(and expr expr ...)
Evaluates from left to right, stops as soon as #f happens.Otherwise, the last expr is the answer.Examples:(and 42 #f "hello") gives #f(and 42 ’hey "hello") gives "hello"(and) gives #t
(or expr expr ...)
Evaluates from left to right, stops as soon as non-#f happens, andthat’s the answer. Otherwise, the answer is #f.Examples:(or 42 ’hey "hello") gives 42(or (and #f) #f) gives #f(or) gives #f
11 / 33
Local Bindings—Non-RecursiveLocal definitions for use in just one expression.
(let ([x expr1][y expr2])
(+ x y (* 2 x y)))
“Compute x + y + 2xy, where x = expr1 and y = expr2”.
expr1 and expr2 cannot see the local x or y; they see outer names.
(let ([x 3])(let ([x (* x x)]) ; (* 3 3)x))
gives 9 and is not a recursion.
let* allows later bindings to see earlier bindings.
(let* ([x 5][y (+ x 1)]) ; (+ 5 1)
(+ x y (* 2 x y)))
12 / 33
Local Bindings—Recursiveletrec allows recursive bindings (self or mutually).
(letrec ([fac(lambda (n)(if (= n 0) 1 (* n (fac (- n 1)))))]
[even(lambda (n)(or (= n 0) (not (odd (- n 1)))))]
[odd(lambda (n)(not (even (- n 1))))])
(even (fac 5)))
13 / 33
Recommended Code LayoutJokes: Pythonic Scheme inspired by Pythonic Java.
Serious:
I Open parentheses then immediately first word.I Procedure definition: Body starts on new line, indented.I Long expression: Parts start on new lines, indented.I Closing parentheses not on new lines.
Most editors have Scheme modes that can do these for you.
Compound Data: Pairs And Lists“Cons cell”, 2-tuple, pair. Syntax: (cons x y).Can imagine a pair of pointers.Short-hand if both fields are literals: ’(5 . "hello").
What if the 2nd field is (points to) a cons cell again, and its 2ndfield is a cons cell again,. . . ? Singly-linked list.
Special support for lists:
I Empty list: ’()I (list x y z) = (cons x (cons y (cons z ’())))I List literal: ’(42 "hi" Chrome)
The Chrome means the symbol ’Chrome.
15 / 33
Some Pair And List OperationsTests: pair?, list?, null?
First field of a pair: carSecond field of a pair: cdr
First item of a list: first, same answer as car, but only for lists.Tail of a list: rest, same answer as cdr, but only for lists.
Aside: (format "~a = ~a~n" "price" 5) gives the string ratherthan outputs it.
(read-line)
(read-string 10) reads up to the upper bound.If EOF, returns eof, can use eq? or eof-object? to test.
stderr:eprintf is like printf but goes to stderr.
19 / 33
Input And Output: PortsRacket has ports, analogous to Java Reader/Writer—behind it canbe file, string, network connection, message queue, user-defined.
Control-flow jumps into f; later automagically knows where toreturn to.
“Sufficiently elegant solutions are indistiguishable from magic.”
A stack is used to remember where to return to. “Call stack”.
Benefit: Supports recursion (self and mutual).Price: Each invocation holds up Θ(1) space until it finishes.
(Invented by Peter Naur for Algol. Before him, each procedure wasgiven fixed space for return address. Recursion disallowed. Peopledidn’t believe Naur when he got this to work.)
You will understand this intimately in Part II of the course.
31 / 33
Non-Tail Calls and Tail CallsNon-tail call: There is post-processing after the call returns.
(define (my-sum lst)(match lst [’() 0]
[(cons hd tl) (+ hd (my-sum tl))]))
Takes Θ(n) space (if n is the list length).
Tail call: No post-processing after the call returns. No need toremember return address, just jump.