1

我很难理解如何为 lambda 表达式的作业问题构建解决方案。我必须编写一个函数,它接受一个参数 F,它是一个谓词函数,并返回一个新函数,它是 F 的逆函数。

我知道在我的函数的某个地方,我会从传入的谓词函数中返回值的 not 以返回相反的结果,但我对问题描述的其余部分感到困惑。问题指出“您将需要一个 lambda 内的 lambda。由于您不知道 F 将采用多少个参数(实际上可能采用一个变量数),您将不得不使用 apply 和定义 lambda 表达式的语法接受任意数量的参数”

我不明白如何设置嵌套的 lambda 表达式来做我想做的事情,返回 F 可能是的逆函数。我一直在尝试一些不同的东西,只是为了看看我是否可以到达任何地方,但我不明白嵌套的 lambda 表达式如何工作到足以让我到达任何地方。

(define converse
  (lambda (F) 
    (lambda
      (apply (not (F))))))

我知道这行不通,但我需要帮助了解如何设置我的嵌套 lambda 表达式来做我想做的事。

4

1 回答 1

6

You're very close to the answer:

(define converse
  (lambda (f)
    (lambda args
      (not (apply f args)))))

Basically, you were missing the args argument for the innermost lambda, which will hold the variable number of arguments that f can receive. And the not is to be applied after calling f on the arguments. For example, take this predicate with two arguments:

(define (test x y)
  (> x y))

See how it normally works:

(test 10 5)
=> #t
(test 5 10)
=> #f
(test 10 10)
=> #f

And now see how it works after converse has been applied to test. Notice that it had no problem dealing with two arguments:

((converse test) 10 5)
=> #f
((converse test) 5 10)
=> #t
((converse test) 10 10)
=> #t

As a side note: in Racket, the converse procedure we just implemented already exists, and it's called negate. We could implement converse as easily as this:

(define converse negate)
于 2013-06-25T20:42:19.347 回答