higher order procedure to print alternating pictur

2019-09-08 17:11发布

问题:

definition of task : i have to make pumpkins and fishes hanging on a string

terms used :

what-is-it? ==>a function that determines whether to make a fish or a pumpkin

fish-squared ==> a function to make a fish using 2 parameters

pumpkin ==> a function to make a pumpkin with also 2 parameters

decorations ==> a function that appends all the images together

hang-by-thread ==> a function that hangs all the images to a thread

extra

for this exercise i have to use"(if (odd? k) fish-square pumpkin))" EXACTLY like that

problem

when i execute my program it takes a while and then crashes, so i suspect it of being trapped in a loop

code :

(define (fun-string n r)
    (define (what-is-it k)
        (if (odd? k) fish-squared pumpkin))
    (define (decorations k)
        (ht-append ((what-is-it k) r r)
            (decorations (- k 1))))
    (hang-by-thread (decorations n)))

goal :

the goal of this exercise is to learn how to pass-trough functions as parameters, something that scheme is able to do.

many thanks

EDIT*

i have added the base line, still the same problem, here is all the code :

(define (lampion r l)
  (vc-append (filled-rectangle 2 l) (pumpkin r)))

(define (hang-by-string pumpkins)
  (vc-append (filled-rectangle (pict-width pumpkins) 2)
             lampionnetjes))    

(define (fish-square wh l)
  (vc-append (filled-rectangle 2 l) (fish wh wh)))

(define (fun-string n r)
  (define (what-is-it k)
    (if (odd? k) fish-square pumpkin))
  (define (decorations k)
    (if (= k 1) fish-square)
    (ht-append ((what-is-it k) r r)
               (decorations (- k 1))))
  (hang-by-string (decorations n)))

回答1:

You haven't implemented uselpa's suggestion by doing

(define (decorations k)
  (if (= k 1) fish-square) ; the results of this line are discarded
  (ht-append ((what-is-it k) r r)
             (decorations (- k 1))))

because you discard the result so of the if statement and return the value of

(ht-append ((what-is-it k) r r)
           (decorations (- k 1)))

just like in the original code. The conditional has the form

(if test
  then-part
  else-part)

so what you need is

(define (decorations k)
  (if (= k 1)
    fish-square
    (ht-append ((what-is-it k) r r)
               (decorations (- k 1)))))


回答2:

Looks like you are missing the base case in procedure decorations. You should test whether k <= 0, and stop.



标签: scheme racket