[英]Implementing a for loop in racket
I have been trying to implement a for loop inside a recursive function using a for loop. 我一直在尝试使用for循环在递归函数内实现for循环。 Using the already implemented "for" in racket is not permitted. 不允许在球拍中使用已经实施的“ for”。 Is there a way to implement such a case? 有办法实现这种情况吗?
Note : I am using an Intermediate Student Language for the same. 注意:我使用的是中级学生语言。
First off for
in #lang racket
is purely for side effects. 首先for
在#lang racket
纯粹是为了副作用。 Usually you would want the other variants like for/map
and for/fold
that ends up producing a value. 通常,您会希望其他变量如for/map
和for/fold
最终产生一个值。
Racket is a descendant of Scheme and all looping in it is just syntactic sugar for a recursive function being applied. Racket是Scheme的后代,所有循环都只是应用递归函数的语法糖。 As an example the do
loop: 例如, do
循环:
(do ((vec (make-vector 5))
(i 0 (+ i 1)))
((= i 5) vec)
(vector-set! vec i i))
; ==> #(0 1 2 3 4)
In reality the language doesn't have do
as a primitive. 在现实中,语言没有do
一个原始的。 Instead the implementation usually have a macro that makes it into this (or something similar): 取而代之的是,实现通常具有一个使它包含在其中的宏(或类似的东西):
(let loop ((vec (make-vector 5)) (i 0))
(if (= i 5)
vec
(begin
(vector-set! vec i i)
(loop vec (+ i 1)))))
This is of course just sugar for this: 当然,这只是糖:
((letrec ((loop (lambda (vec i)
(if (= i 5)
vec
(begin
(vector-set! vec i i)
(loop vec (+ i 1)))))))
loop)
(make-vector 5) (i 0))
And of course letrec
is also sugar... It goes down to just using lambda
at some level. 当然, letrec
也是糖。它可以归结为只是在某种程度上使用了lambda
。
Here is an example. 这是一个例子。 The function squares
produces a list of the first n
square numbers. 函数squares
产生前n
平方数的列表。 To produce that list, it loops over the number 0, ..., n-1 using an index i
. 为了产生该列表,它使用索引i
遍历数字0,...,n-1。
(define (squares n)
(define (loop i)
(if (= i n)
'()
(cons (* i i) (loop (+ i 1)))))
(loop 0))
(squares 10)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.