how to access a value inside a nested structure

I am having problems how do you access a definition inside a structure inside of a structure?

(define-struct health (maximum current))
;; A Health is a (make-health Nat Nat)
;; Requires:
;;    current <= maximum

(define-struct weapon (strike-damage durability))
;; A Weapon is a (make-weapon Nat Health)
;; Requires:
;;    strike-damage > 0

;; The Hero's rupee-total field is the total balance of rupees
;; (i.e., the in-game currency) possessed by the Hero
(define-struct hero (sword life rupee-total))
;; A Hero is a (make-hero Weapon Health Nat)

(define damaged-broadsword (make-weapon 5 (make-health 10 5)))

(define (total-damage sword)
  (* (weapon-strike-damage sword) (weapon-durability sword)))

I am trying to multiply the current health of the sword with strike-damage to do that I have to access durability, with has 2 values, maximum and current

Upvotes: 0

Views: 423

Answers (1)

Gwang-Jin Kim
Gwang-Jin Kim

Reputation: 10163

You do it by nesting the accessors:

(define (total-damage sword)
  (* (weapon-strike-damage sword)
     (health-current (weapon-durability sword))))

Maybe more readable:

(define (total-damage sword)
  (let* ((dmg (weapon-strike-damage sword)) ;; get damage value of sword
         (h   (weapon-durability sword))    ;; get sword's health-struct 
         (c   (health-current h)))          ;; get current health out of 
    (* dmg c)))                             ;; the health struct and calculate

;; so from your example:
(total-damage damaged-broadsword)
;; 25

Upvotes: 1

Related Questions