Using an parameters as instanced within structure

53 Views Asked by At

I am currently completing chapter 7 of the htdp book and am trying to create an instance of the spider structure:

#lang racket
;; spider-structure: structure -> ???
;; defines a spider structure with two parameters: legs and volume
(define-struct spider (legs volume))
;; spidercheck: lambda -> num
;; creates a spider check function and determines volume based on legs
(define spidercheck
 (lambda (legs)
  (cond
   ((<= legs 4) 800)
   ((> legs 4) 1000))))
(define a-spider
 (make-spider 4
              (spidercheck ...

My problem is that I want to pass the number from (make-spider 4) to the spidercheck function within the a-spider function. I have tried (spider-legs a-spider) but of course it says it is used before its definition. Any help is appreciated.

Thanks!

2

There are 2 best solutions below

3
On BEST ANSWER

A simplistic solution would be to call make-spider and spidercheck with the same parameter, let's say the number 2:

(define spiderman (make-spider 2 (spidercheck 2)))

A more interesting alternative would be to define a new function that enforces the restriction that the same n, the number of legs, is passed as parameter for both make-spider and spider check:

(define a-spider
  (lambda (n)
    (make-spider n (spidercheck n))))

Now, whenever you want to create a spider you can specify just the number of legs as parameter, and let spidercheck take care of calculating the volume. Also notice that you can simplify the above snippet even more, using the define syntax that makes the lambda implicit:

(define (a-spider n)
  (make-spider n (spidercheck n)))

Either way, to create a new spider (for instance, with 8 legs) do this:

(define charlotte (a-spider 8))
0
On

Try using let and reusing the number 4 that way. I'm not too sure how the book is handling spiders but you might need this pattern:

(define a-spider
  (let ([a-legs 4])
    (make-spider a-legs (spidercheck a-legs))))

This answer is inferior to Oscar's as it hardcodes the number of legs a spider has. But it does show one way to reference a value multiple times.