【问题标题】:How to use a map function with variables in racket (define)如何在球拍中使用带有变量的地图函数(定义)
【发布时间】:2021-09-17 13:22:13
【问题描述】:

所以我有一个问题要解决。

编写一个名为 parity 的函数,它接受四个数字,其中每个 number 是 0 或 1,并产生另一个数字,即 0 或 1。如果有奇数,您的函数应该产生 1 输入数字中的个数,如果有偶数个,则为 0。

我正在尝试使用 map 函数以迂回的方式执行此操作,目前位于

(define (parity a b c d)
  (map (lambda (thing)
         (positive? thing))
       '(a b c d)))

然后我想以某种方式仅使用正数创建一个新列表,然后找到长度,然后将其等同于 01。但是,由于positive? 搜索数字并找到a,我的代码在定义后不起作用。

【问题讨论】:

  • 引用列表'(a b c d) 是一个列表文字,所以无论您提供什么输入abcd,lambda 都会映射到列表@987654332 @。相反,使用(list a b c d) 在运行时创建一个列表。

标签: racket


【解决方案1】:

第一个错误已经在 cmets 中提到了——而不是 '(a b c d),使用 (list a b c d) 来获取符号的值。

有两种方法可以获得所需的输出,其中任何一种都不需要map

  • 我可以按照您的思路,使用这些功能:

仅使用正数创建一个新列表 -> filter

然后求长度 -> length

然后将其等同于 0 或 1。 -> odd?/even? 长度或 modulo

(define (parity a b c d)
  (let* ((only-positive (filter positive? (list a b c d)))
        (len (length only-positive)))
    (if (odd? len) 1 0)))

这可以缩短为

(define (parity a b c d)
  (if (odd? (length (filter positive? (list a b c d)))) 1 0))

请注意,该问题描述几乎与此解决方案完全匹配:if (odd (number of (ones in the input numbers))) 1 0.

  • apply 的更短解决方案:
(define (parity a b c d)
  (modulo (apply + (list a b c d)) 2))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-03
    • 1970-01-01
    • 2014-11-02
    • 2022-12-18
    • 1970-01-01
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多