2

我无法在 Scheme 中编写一个函数,该函数在不使用任何赋值语句的情况下返回列表中的奇数个数。我正在尝试使用谓词奇数?也是。任何帮助/提示将不胜感激。

例如: (odds '(1 2 3 4 5) // 返回 3

此外,该列表是整数

4

5 回答 5

4

好吧,如果不能使用赋值语句,您仍然可以使用内置过程。特别是,count将在 Racket 中很好地工作:

(define (odds lst)
  (count odd? lst))

...但我猜你应该从头开始实施解决方案。自行寻找解决方案的一些提示,请填空:

(define (odds lst)
  (cond (<???>                 ; if the list is empty
         <???>)                ; then how many odd numbers are in it?
        ((odd? <???>)          ; if the first element is odd
         (<???> (odds <???>))) ; then add one and advance recursion
        (else                  ; otherwise
         (odds <???>))))       ; just advance the recursion

无论如何,它按预期工作:

(odds '(1 2 3 4 5))
=> 3
于 2013-06-25T18:44:33.147 回答
1

无论您使用 (R6RS?) Scheme 还是 Racket,这两者都适用:

(define (odds lst)
  (length (filter odd? lst)))

(define l '(1 2 3 4 5 6 7 8 9 10))
(odds l)
于 2013-06-25T20:10:00.313 回答
0

这是另一个单线

(define (odds L)
 (reduce + 0 (map (lambda (x) (if (odd? x) 1 0)) L)))
于 2013-06-25T23:12:40.740 回答
0

这是一个函数,它返回一个基于谓词计算任何内容的函数:

(define (counter-for predicate)
  (define (counting list)
    (if (null? list)
        0
        (+ (if (predicate (car list)) 1 0)
           (counting (cdr list)))))
   counting))

使用如下:

(define odds (counter-for odd?))

[更多选项]这是一个不错的递归解决方案

(define (odds list)
  (if (null? list)
      0
      (+ (if (odd? (car list)) 1 0)
         (odds (cdr list)))))

这是一个尾递归解决方案:

(define (odds list)
  (let odding ((list list) (count 0)))
    (if (null? list)
        count
        (odding (cdr list)
                (+ count (if (odd? (car list)) 1 0))))))

这是一个基于谓词计算任何内容的例程:

(define (count-if predicate list)
  (if (null? list)
      0
      (+ (if (predicate (car list)) 1 0)
         (count-if predicate (cdr list)))))
于 2013-06-26T03:14:47.510 回答
0

尽可能低的水平:

(define odds
  (lambda (lst) 
    (cond ((empty? lst) 0)
          ((not (= 0 (modulo (car lst) 2))) (+ 1 (odds (rest lst))))
          (else (odds (cdr lst))))))
于 2013-06-25T22:41:30.333 回答