【问题标题】:How can i get the positive even elements in scheme我怎样才能在方案中获得积极的偶数元素
【发布时间】:2022-01-06 07:00:34
【问题描述】:

我正在尝试在方案中获得所有均匀和积极的元素

我有以下代码

(define (getVals  lis)
  (cond
    ((null? lis) lis)
    (((> (car lis) 0) (even? (car lis)))
     (cons (getVals (cdr lis))))
    )
  )

检查我的代码我正在使用

getVals '(2 -2 4 6 5))

应该输出一个包含正数和偶数的新列表 (2 4 6)

谢谢

【问题讨论】:

    标签: scheme racket


    【解决方案1】:

    只是为了补充@OscarLopez 的答案-如果您再看一眼,您会发现getVals 只是`filter 的特定情况。

    (define (getVals lis)
      (cond
        ((null? lis) lis)
        ((and (even? (car lis)) (positive? (car lis)))
         (cons (car lis) (getVals (cdr lis))))
        (else (getVals (cdr lis)))))
    

    对比:

    (define (filter func lst)
      (cond
        ((null? lis) lst)
        ((func (car lst))
         (cons (car lst) (filter func (cdr lst))))
        (else (filter func (cdr lst)))))
    

    filter func 设为getVales,并且 func 为:

    (lambda (x) (and (even? x) (positive? x)))
    

    getVals 只是过滤器的一个特例:

    (define (getVals lst)
      (filter (lambda (x) (and (even? x) (positive? x))) lst))
    

    但是你应该遵循 Lisp 语言的风格指南 - 不要使用 camelCase 作为函数名,但更喜欢 lisp 类型的形式 get-vals

    【讨论】:

      【解决方案2】:

      最简单的方法是使用内置程序:

      (define (getVals lis)
        (filter (lambda (x) (and (even? x) (positive? x)))
                lis))
      

      如果你想从头开始实现它,你需要修复你的代码:

      • 缺少当前元素满足条件的情况(else 情况)。
      • 调用cons时缺少一个参数。
      • 条件缺少and

      这就是我的意思:

      (define (getVals lis)
        (cond
          ((null? lis) lis)
          ((and (even? (car lis)) (positive? (car lis)))
           (cons (car lis) (getVals (cdr lis))))
          (else (getVals (cdr lis)))))
      

      无论哪种方式,它都按预期工作:

      (getVals '(2 -2 4 6 5))
      => '(2 4 6)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-07
        • 2011-06-04
        • 1970-01-01
        • 2017-05-25
        • 2023-01-04
        相关资源
        最近更新 更多