无法获得Y组合器的实现工作 [英] Unable to get implementation of Y combinator working

查看:134
本文介绍了无法获得Y组合器的实现工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是代码(。


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?

解决方案

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" .

这篇关于无法获得Y组合器的实现工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆