【问题标题】:Trying to output a list but instead getting a single value试图输出一个列表,但得到一个值
【发布时间】:2021-03-27 07:23:07
【问题描述】:
  • 我正在尝试创建一个函数来比较两个字符串列表并将比较结果保存到一个列表中
  • 结果以布尔值形式给出 没有错误消息,而不是输出是具有多个布尔结果的列表,我只得到一个结果
; alon: a list of names
; alob: a list of boolean 
(define (findNamev4 alon alon2 alob)  
  (cond
    [(empty? alon) #false]
    [(string=? (first alon) (first alon2)) (cons #true lob)]
    [else (findNamev4 (rest alon) (first (rest alon2)) alob)]))
    
    
(findNamev4 l1 l2 lob)
(findNamev4 l2 l2 lob)
  • 输出不是一个列表,而是一个布尔值
(list #true)
(list #true)
(list #true)

【问题讨论】:

  • 为什么要传递(first (rest alon2)) 作为递归步骤的第二个参数?
  • 你能显示输入和预期输出吗?

标签: list functional-programming racket


【解决方案1】:

我建议这样做:

(define (compare-string-lists strs-1 strs-2)
  (cond
   [(or (empty? strs-1) (empty? strs-2)) empty]
   [else
    (cons (string=? (first strs-1) (first strs-2))
          (compare-string-lists (rest strs-1) (rest strs-2)))]))

您没有指定如果列表的长度不同会发生什么;此版本将仅比较两个列表中较短的一个中存在的元素。

解释:

  • 第一个案例是我们的基本案例。如果两个列表中的任何一个为空,则我们不需要将比较添加到比较列表中,因此我们可以返回一个空列表。
  • 第二种情况是我们的递归情况。我们想要比较每个列表的第一个元素,然后将结果(使用cons)附加到包含输入列表其余部分的比较结果的列表中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-07
    • 1970-01-01
    • 1970-01-01
    • 2019-07-18
    • 1970-01-01
    相关资源
    最近更新 更多