[plt-scheme] Was HTDP 21.1.2 - Why I "don't" use the designrecipe, etc.

From: wooks . (wookiz at hotmail.com)
Date: Sat Jul 15 10:16:12 EDT 2006





>>
>>Maybe I should ask the question that struck me immediately I saw this 
>>problem. Why would I want to do this anyway. Map and fold are clearly 
>>intuitive one is a translation the other is a summarisation. I cannot 
>>intuitively see why I would want to implement a translation in terms of a 
>>summarisation.
>
>Perhaps because you were in an environment that provided one and not the 
>other?  That kind of thing certainly happens in the real world.
>
>Of course, the real, pedagogical reason for the problem is to expand the 
>reader's conception of higher-order functions and their applicability.  To 
>point out that "fold" CAN be usefully used with S and T being different 
>types -- exactly the lesson you're trying to learn.
>
>>>Once again, the X's and Y's in the contract for fold are independent  
>>>from the X's and Y's for map, and we could instantiate it ...
>>>...snip...
>>>The names don't matter at all; in fact, we could instead use the names S 
>>>and T:
>>>
>>>;; fold : forall S, T . T (S T -> T) [Listof S] -> T
>>
>>I would more readily accept this with an example of a case where we 
>>summarised 2 different types of data - but lets see.
>
>Well, "map" is a good example, but that's what you're having trouble with 
>already.  Let's try a more prosaic example: use "fold" to write a 
>"highest-salary" function on a list of employees.  The input is a list of 
>employees, so S must be "employee"; the output is a number, so T must be 
>"number".
>


(define (fold op baseCase a-list)
  (cond
    [(empty? a-list) baseCase]
    [else (op (first a-list)
	     (fold op baseCase  (rest a-list)))]))

(define-struct emp (name salary))

(define (highestSalary emps)
  (fold >emp 0 emps))

;>emp : employee number -> number
;returns the greater of the employees salary and the number
(define (>emp x y)
  (cond
    [(< (emp-salary x) y)  y]
    [else (emp-salary x)]))

Map is not yet obvious ..but I'm thinking of breakfast.




Posted on the users mailing list.