简体   繁体   English

在球拍中用Lambda进行迭代?

[英]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: 您的代码有两个问题:

  • The call to helper must be surrounded by () , because that's how you call a procedure in Scheme. helper的调用必须被()包围,因为这就是您在Scheme中调用过程的方式。
  • The initial value for the accumulator must be an empty list given that we're building a list as the output, not a 0 as you had it. 假设我们正在构建一个列表作为输出,则累加器的初始值必须为空列表,而不是像原来那样为0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM