Rachel
Rachel

Reputation: 31

Scheme: using a procedure within a procedure or how to count the number of occurrence of each element

(require (planet dyoo/simply-scheme:1:2/simply-scheme))

(define (ball-val value)
   (let ((color value))
       (cond ((equal? 'R color) 5)
             ((equal? 'W color) 2)
             ((equal? 'B color) 2)
             ((equal? 'G color) 1))))

(define (count-balls color bucket)
    (count (keep (lambda (c) (equal? color c)) bucket)))

The two procedures give the value of each colored ball and counts the number of balls in a bucket given a specific color.

Another procedure called color-counts needs to be written to output a sentence of number of each colored ball in a bucket, given that the only parameter is a bucket of balls.

Write a procedure color-counts that takes a bucket as its argument and returns a sentence containing the number of reds, the number of green, the number of blues, and the number of whites in the bucket.

ex:

  (color-counts '(R B G R R R B W R W))
    '(5 1 2 2)

  (color-counts '(W R R R R G B B G W))
    '(4 2 2 2)

Is it possible to call count-balls in a color-count and just call count-balls for each color in color-count? or is that not possible?

I tried:

(define (color-counts bucket) 
  (count-balls 'R bucket count-balls 'W bucket count-balls 'B bucket count-balls 'G bucket)) 

All I get is:

#<procedure ...>

Upvotes: 0

Views: 366

Answers (1)

Barmar
Barmar

Reputation: 781190

You can call any procedure you like from any other procedure.

You're calling count-balls incorrectly. It only takes 2 arguments, but you're calling it with 11 arguments. You need to write separate calls for each color, not put them all in one call. And you need to wrap that in a call to list to create a list of all the results.

(define (color-count bucket)
  (list (count-balls 'R bucket)
        (count-balls 'G bucket)
        (count-balls 'B bucket)
        (count-balls 'W bucket)))

You can also use the map function to remove all the repeated code:

(define (color-count bucket)
  (map (lambda (color) (count-balls color bucket))
       '(R G B W)))

map calls the procedure repeatedly with each element of the list (R G B W) as its argument, and returns a list of all the results.

Upvotes: 0

Related Questions