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.
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
. Any pointers? I'm new to racket/scheme.
The most idiomatic solution in Racket would be:
(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. 0
as you had it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.