;; ------------------------------------------------------------------------- ;; Exploring the idea of a "finite function" (Session 23) ;; ------------------------------------------------------------------------- #lang racket ;; ------------------------------------------------------------------------- ;; a finite function implemented as a Racket function ;; ------------------------------------------------------------------------- (define (f arg) (cond ((eq? arg 'foo) 2) ((eq? arg 'bar) 5) ((eq? arg 'baz) 15) (else (error 'ff "no such key -- ~a" arg)))) ;; ------------------------------------------------------------------------- ;; a finite function that extends an existing finite function named f ;; with a new ordered pair: (bif, 64) ;; ------------------------------------------------------------------------- (define (f-plus-bif arg) (cond ((eq? arg 'bif) 41) (else (f arg)))) ;; ------------------------------------------------------------------------- ;; a function that extends *any* finite function with the pair (bif, 41) ;; ------------------------------------------------------------------------- (define (extend-with-bif ff) (lambda (arg) (cond ((eq? arg 'bif) 41) (else (ff arg))))) ;; ------------------------------------------------------------------------- ;; [ ... later, after we talk about the finite function ADT ... ] ;; ------------------------------------------------------------------------- ;; We can build our original finite function f from scratch using ;; the finite function ADT. ;; ------------------------------------------------------------------------- (require "finite-function.rkt") (define my-ff (extend-ff 'foo 2 (extend-ff 'bar 5 (extend-ff 'baz 15 (empty-ff) )))) ;; ------------------------------------------------------------------------- ;; This is what my-ff looks like, after using program derivation to show ;; the functions that are created by the finite function ADT. ;; ------------------------------------------------------------------------- (define my-ff-expanded (lambda (symbol) (if (eq? symbol 'foo) 2 ((lambda (symbol) (if (eq? symbol 'bar) 5 ((lambda (symbol) (if (eq? symbol 'baz) 15 ((lambda (symbol) (error 'ff "no such key -- ~a" symbol)) symbol))) symbol))) symbol)))) ;; ------------------------------------------------------------------------- ;; No, we wouldn't want to write that by hand. :-) But if a program ;; generates it for us, we can be happy to use it through the finite ;; function interface! ;; -------------------------------------------------------------------------