Lecture overview -- Keyboard shortcut: 'u'  Previous page: Example with cond: <kbd>american-time</kbd> -- Keyboard shortcut: 'p'  Next page: Recursion and iteration [Section] -- Keyboard shortcut: 'n'  Lecture notes - all slides and notes together  slide -- Keyboard shortcut: 't'  Textbook -- Keyboard shortcut: 'v'  Help page about these notes  Alphabetic index  Course home    Lecture 3 - Page 14 : 42
Functional Programming in Scheme
Name binding, Recursion, Iteration, and Continuations
Example with cond: as-string

(define (as-string x)
  (cond ((number? x) (number->string x))
        ((symbol? x) (symbol->string x))
        ((string? x) x)
        ((boolean? x) 
            (if x "true" "false"))   ; consider "#t" and "#f" as alternatives
        ((char? x) (char->string x))
        ((list? x)
            (string-append "(" 
               (string-merge (map as-string x) (make-list (- (length x) 1) " "))
               ")"))
        ((vector? x)
          (let ((lst (vector->list x)))
            (string-append "#(" 
               (string-merge (map as-string lst) (make-list (- (length lst) 1) " "))
               ")")))
        ((pair? x)
            (string-append "(" 
               (apply string-append
                  (map (lambda (y) (string-append (as-string y) " ")) (proper-part x))
               )
               " . " (as-string (first-improper-part x))
               ")"))
        (else "??")))

The function as-string converts a variety of Scheme data types to a string. This function makes use of the fact that any kind of data can be passed to the function, without intervening static type check. At run time we dispatch on the type of x. The function string-merge is discussed later in this section, cf. the reference from this page. The function as-string, and its sibling functions as-number, as-char, as-symbol, and as-list are used heavily in all LAML software. The functions are convenient because they do not need to know the type of the input data. In functional languages with static type checking, we cannot program these functions as shown above. In these language we could overload the function name as-string, and underneath define a number of individual functions each taking a particular type of input.