我正在尝试通过结构列表编写一个简单的搜索。我目前的代码意味着接受一个星球并搜索我现有的小清单,找到匹配的结构并显示该星球的质量。目前使用Dr. Racket编译器显示整个列表。我不确定为什么,并希望得到任何帮助。
#lang scheme
(define-struct celestialbody
(
name
mass
radius
)
#:transparent
)
(define bigG .00000000006673)
(define (newCelestialBody name mass radius)
(make-celestialbody name mass radius))
(define SolarSystem
(list
(newCelestialBody "Sun" 1988550000000000000000000000000 695700)
(newCelestialBody "Mercury" 330110000000000000000000 2439.7)
(newCelestialBody "Venus" 4867500000000000000000000 6051.8)
(newCelestialBody "Earth" 5972370000000000000000000 6371)
(newCelestialBody "Moon" 7342000000000000000000 1737.1)
(newCelestialBody "Mars" 641710000000000000000000 3389.5)
(newCelestialBody "Jupiter" 1898600000000000000000000000 69911)
(newCelestialBody "Saturn" 568360000000000000000000000 58232)
(newCelestialBody "Uranus" 86810000000000000000000000 25362)
(newCelestialBody "Neptune" 102430000000000000000000000 24622)
)
)
(define (find-mass planet system)
(if(empty? list)
(#f)
(if(string-ci=? (celestialbody-name (first system)) planet)
(celestialbody-mass (first system))
(find-mass planet (rest system))
)
)
)
答案 0 :(得分:0)
搜索过程中的基本情况是错误的,您应该使用cond
而不是嵌套if
。除此之外,代码看起来很好:
(define (find-mass planet system)
(cond ((empty? system) #f)
((string-ci=? (celestialbody-name (first system)) planet)
(celestialbody-mass (first system)))
(else (find-mass planet (rest system)))))
例如:
(find-mass "Saturn" SolarSystem)
=> 568360000000000000000000000