![]() |
![]() |
|
home—info—lectures—exams—archive
We already saw (define fave-color "teal") (define class-size 17) `define` attaches a value to a place-holder(constant). We also saw calling functions, prefix notation (and, images as values): (sqrt 25) (define circ1 (circle 25 'solid 'orange)) (overlay circ1 (rectangle 15 20 'outline 'black))define for functions
New: We can also define functions: ; intensify: string -> string ; Given an adjective phrase, return a more intense version. ; (define (intensify adj) (string-append "very, very " adj)) Note how 'define' has two flavors: associate a name with a value; associate a name with a function. Wait, these are the same! We'll see more in a second. There is a built-in function "if": ; pluralize: (-> number string string) ; (define (pluralize num noun) (if (= num 1) (string-append (number->string num) noun) (string-append (number->string num) noun) "s")) Compare to the Java version. Another way: remember that 'if' is a function: ; pluralize: (-> number string string) ; (define (pluralize num noun) (string-append (number->string num) noun (if (= num 1) "" "s"))) Q: Java's "if"? is a statment, but Java does have an expression version. What is it? A: ?: (Though this infix notation suddenly interacts with precedence.) 2 + y ? 3 : 5 + 4 (Exercise: come up with an expression of nested ?: which is difficult to parse w/o knowing precedence.)lambda
We can create a function, without naming it: (lambda (x) (+ x x x)) = (lambda (x) ...) ((lambda (x) (+ x x x)) 7) = 21 Is this a mere curiosity? No, it's very handy; we'll see it used later! (For now: reflect on java's Comparable interface, or the command pattern in general.) Note that (define (f x) ...) is syntactic sugar for (define f (lambda (x) ...)) And we are back to a single conceptual use of 'define': attach a name to a placeholder. (The name 'f' is a constant. Cf. Java.)
home—info—lectures—exams—archive
©2008, Ian Barland, Radford University Last modified 2008.Sep.10 (Wed) |
Please mail any suggestions (incl. typos, broken links) to ibarland ![]() |
![]() |