Reputation: 565
I am trying to understand exactly what it does (in scheme), but it doesn't make much sense. Could somebody maybe try to explain it in simple terms? It would be greatly appreciated!
The problem in question
We will be represent a country by using these parameters: GDP in billions of dollars, area in millions of square miles, and population in millions. Write a message-passing procedure (make-country-mp gdp area population) that returns an object that responds to the following messages:
• 'gdp ; simply return the gdp
• 'area ; simply return the area
• 'population ; simply return the population
• 'pop-density ; return population divided by the area
• 'gdp-per-capita ; return the gdp divided by the population
• 'is-bigger ; returns a procedure that takes in another country message-passing object and returns the scheme boolean true if the area of the first county (the original one) is greater than the area of the second country (the one being passed in), otherwise false.
Side note: I do have working code for the majority of the problem, but I would just like an explanation for how it works. All I had to do was follow the general form for the way that message passing works, but I dont understand any of it whatsoever. Here it is
(define (make-country-mp gdp area population)
(define (dispatch msg)
(cond ((equal? msg 'gdp) gdp)
((equal? msg 'area) area)
((equal? msg 'population) population)
((equal? msg 'pop-density) (/ population area))
((equal? msg 'gdp-per-capita) (/ gdp population))
;((equal? msg 'is-bigger) ; unsure of the code here
(else (error "invalid option" msg))))
dispatch)
Upvotes: 0
Views: 144
Reputation: 223003
Basically, make-country-mp
returns a function object (a closure, in this case, which remembers the values for gdp
, area
, and population
that were passed into the make-country-mp
call), which you can call with one argument. The argument is matched against the symbols gdp
, area
, population
, pop-density
, gdp-per-capita
, and is-bigger
, and the appropriate result is returned in each case.
If you know case
, you may find that easier to read:
(define (make-country-mp gdp area population)
(lambda (msg)
(case msg
((gdp) gdp)
((area) area)
((population) population)
((pop-density) (/ population area))
((gdp-per-capita) (/ gdp population))
((is-bigger) (lambda (rhs)
(> area (rhs 'area))))
(else (error "invalid option" msg)))))
Upvotes: 2