我在如何访问结构内部结构中的定义时遇到问题?
(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)))
我正在尝试将剑的当前生命值与打击伤害相乘 为此,我必须访问耐久性,它具有2个值,最大值和当前值
答案 0 :(得分:1)
您可以通过嵌套访问器来做到这一点:
(define (total-damage sword)
(* (weapon-strike-damage sword)
(health-current (weapon-durability sword))))
也许更具可读性:
(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