将数字列表与变量进行比较

Compare a list of numbers with a variable

下面的函数旨在将列表(第二个参数)中的每个数字与第一个参数进行比较,对于列表中大于第二个参数的每个数字,计算它和 return 总数列表中大于 'threshold'

的元素数量

我的代码没有 运行 因为我试图了解 Dr. Racket 中的递归是如何工作的,但我似乎无法理解。我只是很沮丧,所以只知道下面的代码不应该接近工作;函数式编程不是我的菜,哈哈

(define (comp-list threshold list-nums)
  (cond [(empty? list-nums) 0]
        [(cons?  list-nums) (let {[my-var 0]}
                              (map (if (> threshold (first list-nums)) 
                                       threshold 2) list-nums ))]))

map 将过程作为第一个参数并将其应用于给定列表中的每个元素。由于您正在计算某些东西,所以列一个清单是错误的。

foldl 将过程作为第一个参数,起始值作为第二个和一个或多个列表。它应用具有元素和起始值(或中间值)的过程,并且该过程决定下一个中间值。例如。你可以用它来计算一个列表:

(define (my-length lst)
  (foldl (lambda (x acc) (+ acc 1))
         0
         lst))

(my-length '(a b c)) ; ==> 3

您可以轻松地将其更改为仅在 x 大于某个阈值时才计数,只需评估 acc 以在您不增加该值时保持不变。

更新

my-length的递归解法:

(define (my-length lst)
  ;; auxiliary procedure since we need
  ;; an extra argument for counting
  (define (aux lst count)
    (if (null? lst)
        count
        (aux (cdr lst)
             (+ count 1))))
  ;; call auxiliary procedure
  (aux lst 0))

必须对 foldl 的过程进行相同的更改,才能仅在某些情况下有效。

(define (comp-list threshold list-nums)
  (cond 
    [(empty? list-nums)  ; there are 0 elements over the threshold in an empty list
     0]
    [(cons?  list-nums)  ; in a constructed list, we look at the the first number
     (cond
       [(< threshold (first list-nums)) 
        (+ 1                                        ; the first number is over
           (comp-list threshold (rest list-nums))]  ; add the rest 
       [else 
        (comp-list threshold (rest list-nums))])])) ; the first number is lower

以下不使用 foldl 的 lambda(并且是递归的)——你能理解它是如何工作的吗?

(define (comp-list threshold list-nums)
  (cond [(empty? list-nums) 0]
        [else
         (cond [(> (car list-nums) threshold) (+ 1 (comp-list threshold (cdr list-nums)))]
               [else (comp-list threshold (cdr list-nums))])]))

已测试:

> (comp-list 1 '(1 1 2 2 3 3))
4
> (comp-list 2 '(1 1 2 2 3 3))
2
> (comp-list 3 '(1 1 2 2 3 3))
0

一个简单的功能开始

#lang racket

(define (comp-list threshold list-nums)
  (define (my-filter-function num)
    (<  num threshold))
  (length (filter my-filter-function list-nums)))

define 替换为 lambda

#lang racket

(define (comp-list threshold list-nums)
  (length (filter (lambda (num) (< num threshold))
                  list-nums)))

Racket 的实现 filter

DrRacket 中突出显示程序名称并右键单击并选择“跳转到其他文件中的定义”将允许查看源代码。 filter的源代码具有指导意义:

  (define (filter f list)
    (unless (and (procedure? f)
                 (procedure-arity-includes? f 1))
      (raise-argument-error 'filter "(any/c . -> . any/c)" f))
    (unless (list? list)
      (raise-argument-error 'filter "list?" list))
    ;; accumulating the result and reversing it is currently slightly
    ;; faster than a plain loop
    (let loop ([l list] [result null])
      (if (null? l)
        (reverse result)
        (loop (cdr l) (if (f (car l)) (cons (car l) result) result)))))