[英]Iteration with lambda in racket?
This is probably a simple question, but I cannot seem to figure it out. 这可能是一个简单的问题,但我似乎无法弄清楚。 In the example below, I want to create a function
list-of-obj
that recursively creates a list of items. 在下面的示例中,我想创建一个以递归方式创建项目列表的
list-of-obj
函数。
Example: 例:
> (list-of-obj 'a 5)
'(a a a a a)
The code: 编码:
#lang racket
(define (list-of-obj obj n)
(letrec ((helper
(lambda (obj n result)
(if (> n 0)
(helper obj (- n 1) (cons obj result))
result))))
helper obj n 0))
This, however results in output of 0
. 但是,这导致输出为
0
。 Any pointers? 有指针吗? I'm new to racket/scheme.
我是球拍/计画的新手。
The most idiomatic solution in Racket would be: Racket中最常见的解决方案是:
(make-list 5 'a)
=> '(a a a a a)
That is, you should not reinvent the wheel if a built-in function does what you want. 也就是说,如果内置功能可以满足您的要求,则您不应重新发明轮子。 But if you need to write it from scratch, this should do the trick:
但是,如果您需要从头开始编写,则可以做到这一点:
(define (list-of-obj obj n)
(letrec ((helper
(lambda (obj n result)
(if (> n 0)
(helper obj (- n 1) (cons obj result))
result))))
(helper obj n '())))
There were two problems with your code: 您的代码有两个问题:
helper
must be surrounded by ()
, because that's how you call a procedure in Scheme. helper
的调用必须被()
包围,因为这就是您在Scheme中调用过程的方式。 0
as you had it. 0
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.