Search code examples
functional-programmingschemerackethtdp

Using an parameters as instanced within structure


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!


Solution

  • 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))