代码之家  ›  专栏  ›  技术社区  ›  user7120460

“球拍王国”中的Ormap版本

  •  1
  • user7120460  · 技术社区  · 9 年前

    在“球拍领域”中,作者构建了一个用于教育目的的内置函数。

    其ormap的实现是:

    (define (my-ormap-book pred lst)
      (cond [(empty? lst) #f]
            [else (or (pred (first lst))
                      (my-ormap-book pred (rest lst)))]))
    

    (require rackunit)
    (check-equal? (my-ormap-book add1 '(3 4 5)) 4)
    (check-equal? (my-ormap-book add1 '()) #f)
    (check-equal? (my-ormap-book positive? '(1 2 a)) #t)
    

    然而,真正的Ormap,如racket文档所示- link -还可以使用两个或多个列表作为输入,例如:

    (check-equal? (ormap + '(1 2 3) '(4 5 6)) 5)
    

    当使用“Racket领域”的实现进行测试时,您会得到:

    (check-equal? (my-ormap-book  + '(1 2 3) '(4 5 6)) 5)
    
    my-ormap-book: arity mismatch;
     the expected number of arguments does not match the given number
      expected: 2
      given: 3
      arguments...:
    

    如何使“我的ormap手册”过程通过此测试用例?

    1 回复  |  直到 9 年前
        1
  •  0
  •   coredump    9 年前

    回答第一个问题:定义变量函数有两种方法。最简单的方法是在参数列表中最后一个参数之前使用点:

    (define (f a b . rest-args)
      (first rest-args))
    

    前两个参数之后的所有参数都绑定到具有给定名称的列表中。

    这个完全无用的函数接受两个或多个参数,并返回第三个参数(好吧,无意义 和 破损)。

    回答你的另一个问题…这是一个在相同长度的多个列表上同时递归的问题,我想请你参考 section 23.1 of HtDP 2e .