;; The first three lines of this file were inserted by DrRacket. They record metadata ;; about the language level of this file in a form that our tools can easily process. #reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname lambda-examples) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f))) (require "student-extras.rkt") #| (As lead-in to grammars:) Recall the syntax (grammar) of racket's `define`: ::= (define ) | (define (₁ …) ) Semantics: (a) evaluate ``, and henceforth associate `` with that value (b) do whatever `(define ₀ (lambda (₁ …) ))` means (per case (a)). "Syntactic sugar" means that: the semantics of the new syntax can be easily understood in terms of the semantics for an easier, already-understood syntax. (In this case: creating (an anonymous) function is one "simple" thing, and binding a name to a value is another. The 2nd version of the syntax is simply a convenience/shorthand since these two tasks are often done together.) |# ; Recall that: ; (define (celc2fahr_v1 degC) (+ 32 (* 180/100 degC))) ; is syntactic sugar for: ; (define celc2fahr_v2 (function (degC) (+ 32 (* 180/100 degC)))) (celc2fahr_v2 (+ 10 2)) ; same as: ; ((lambda (degC) (+ 32 (* 180/100 degC))) (+ 10 2)) ; ; In fact, line16 is the first step the computer ; actually does, in evaluating line12. (Try stepper.) (define some-numeric-functions (list sqr positive? number->string)) ((first some-numeric-functions) (+ 10 2)) ; Note the "((" -- we've never seen that before! (define some-numeric-functions_v2 (list sqr positive? number->string (function (len) (make-string len #\z)))) ((fourth some-numeric-functions_v2) (+ 10 2)) ; Q: "is it really clearer, to put that lambda-expr in the list, ; rather than defining&naming the function first, and using ; the name to add it into the list?" ; ; A: When you become accustomed to lambda expressions ; (and perhaps use shorter-hand like "λ" instead of "function", ; or Java's `(len) -> String.make(2,'z')` ) ; then for one-off functions it *is* easier to give an anonymous ; function rather than attach an additional name. ; Compare: Imagine if you couldn't pass the int `17` to any function, ; and instead had to make a var(name) initialized to 17, and then only use the name. ; Another example of higher-order functions: (and/c integer? positive?) ((and/c integer? positive?) 23) ((and/c integer? positive?) -3) ((and/c integer? positive?) "hello") ; Sure you could name this "positive-integer?", but if you're only ; using it once that name is extra overload. ;; Compare from exam, our union-type: ;(define bee (or/c queen? worker? larva?)) ; ; `or/c` makes creating [predicates for] union-types trivial and concise.