You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Racket的define定义中结合变量使用map实现parity奇偶校验函数

问题根因

  • 报错的核心原因是你使用了'(a b c d)构建列表:Racket中单引号'包裹的列表为字面量列表,内部的标识符不会被求值,因此实际传入positive?的是'a、'b这类符号,而非函数入参的数值。
  • 修复第一步是将'(a b c d)替换为(list a b c d),list函数会对所有参数执行求值操作,能拿到传入的0/1实际值。

完整实现方案

方案1(符合你筛选正数再求长度的思路)

直接用filter筛选出所有正数,对长度取2的模即可得到结果:

(define (parity a b c d)
  (modulo (length (filter positive? (list a b c d)))
          2))

方案2(基于你原本想使用map的思路实现)

先通过map把所有1转为1、0转为0,求和后取模:

(define (parity a b c d)
  (modulo (apply + (map (lambda (val) (if (positive? val) 1 0))
                        (list a b c d)))
          2))

测试验证

你可以用以下用例验证正确性:

  • (parity 1 0 0 0) 返回1(1个1,奇数)
  • (parity 1 1 0 0) 返回0(2个1,偶数)
  • (parity 1 1 1 1) 返回0(4个1,偶数)
  • (parity 1 1 1 0) 返回1(3个1,奇数)

内容的提问来源于stack exchange,提问作者Thisbe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 00:27:03