无法实现Y组合器的工作

时间:2012-08-12 18:45:37

标签: functional-programming scheme racket combinators y-combinator

以下是代码(also here):

#lang racket
(define poorY
  ((lambda length
    (lambda (ls)
      (cond
        [(null? ls) 0]
        [else (add1 ((length length) (cdr ls)))])))
  (lambda length
    (lambda (ls)
      (cond
        [(null? ls) 0]
        [else (add1 ((length length) (cdr ls)))])))))

当我运行它时:

> (poorY '(9 7 8))
. . application: not a procedure;
 expected a procedure that can be applied to arguments
  given: '(#<procedure>)
  arguments...:
   '(#<procedure>)

屏幕截图如下所示:

enter image description here

我正在使用DrRacket作为代表。 代码有什么问题?

1 个答案:

答案 0 :(得分:9)

length周围应该有括号:

(define poorY
  ((lambda (length)  ;; here
    (lambda (ls)
      (cond
        [(null? ls) 0]
        [else (add1 ((length length) (cdr ls)))])))
  (lambda (length)   ;; and here
    (lambda (ls)
  ......

您可以尝试

,而不是两次输入相同的长lambda表达式
(define poorY
  ((lambda (f) (f f))
   (lambda (length)
     (lambda (ls)
       (cond
         [(null? ls) 0]
         [else (add1 ((length length) (cdr ls)))])))))

另见Y combinator discussion in "The Little Schemer"