【问题标题】:Iterate through list, displaying whole list遍历列表,显示整个列表
【发布时间】:2016-08-08 04:16:26
【问题描述】:

我正在尝试通过结构列表编写一个简单的搜索。我当前的代码意味着接收一个行星并搜索我现有的小列表并找到匹配的结构并显示该行星的质量。当前使用 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))
      )
   )
)

【问题讨论】:

  • 请正确缩进代码:不要将括号单独放在一行中。

标签: list loops search struct scheme


【解决方案1】:

搜索过程中的基本情况是错误的,您应该使用cond 而不是嵌套ifs。除此之外,代码看起来不错:

(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

【讨论】:

  • 非常感谢。这行得通。非常快速的反应。实际上,我试图根据您 3 年前对 Tim 的回复来弄清楚这一点。
猜你喜欢
  • 2020-12-16
  • 2021-03-19
  • 1970-01-01
  • 2020-09-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多