Unable to get implementation of Y combinator working

你说的曾经没有我的故事 提交于 2019-12-11 07:56:53

问题


Here's the code (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)))])))))

When I run it:

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

The screenshot looks like this:

I'm using DrRacket as the repl. What's wrong with the code?


回答1:


There should be parentheses around length :

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

Instead of typing the same long lambda expression twice, you can also try

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

See also Y combinator discussion in "The Little Schemer" .



来源:https://stackoverflow.com/questions/11924832/unable-to-get-implementation-of-y-combinator-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!