Quiz 3 Key, CS 257

name or user id on aix.unm.edu bap@cs.unm.edu
  1. What values are printed when you type each of the following to Scheme? (2 points each)
    expressionresult
    (every - '(3 -5 -8 13)) (-3 5 8 -13)

    negate all the numbers

    (keep (lambda (x) (< x 10))
          '(1 12 3 14 5 16))
    (1 3 5)

    keep numbers less than 10

    (define (foo x y)
       (+ (last x) (last y)))

    (accumulate foo '(321 432 543))
    6

    sum of last digits, 1+2+3 = 6

    (count (keep even? '(11 12 13 14 15))) 2

    the call to keep returns (12 14), which has two elements

    (+ 10 ((if (equal? 'a 'b) + *) 2 3)) 16

    the equal? returns #f, so the if returns *, so we get (+ 10 (* 2 3)) = (+ 10 6) = 16

  2. Define a function sum-big-ones that takes a sentence of numbers as its sole argument, and returns the sum of all the elements of the sentence greater than 14. (Use higher order functions, not recursion.) (10 points)

    For example (sum-big-ones '(1 20 5 30)) evaluates to 20+30=50.


    ;;; Filter out the words we care about and add em up:
    
    (define (big-one? x)
      (> x 14))
    
    (define (sum-big-ones sen)
      (accumulate + (keep big-one? sen)))
    
    
    
    
    

  3. Extra credit: explain briefly in English what foo does and how it works. (5 points)
    (define (foo sen)
      (accumulate (lambda (x y)
    		(if (> (count x) (count y)) x y))
    	      sen))
    

    The anonymous function returned by lambda takes two words and returns the longer of the two. So foo returns the longest word in the sentence it is passed.

    Because the function defined by the lambda expression favors its second argument when its two arguments have the same length, foo breaks ties to the right.

    Here are some examples, with the length of words written under them to make it easier to see which is the longest:

    (foo '(one two three four))        ->  three
            3   3    5    4
    
    (foo '(one two three four seven))  ->  seven
            3   3    5    4     5
    
    (foo '(one two seven three four))  ->  three
            3   3    5     5    4