How to create a list with n applications of a procedure

泄露秘密 提交于 2019-12-06 08:13:22

Something like this?

#!racket/base
(require srfi/1)

(define (times/list proc n)
  (unfold-right zero? proc sub1 n))

(times/list (lambda (v) (abs (- v 5))) 10)
; ==> (4 3 2 1 0 1 2 3 4 5)

(times/list (lambda _ 5) 10)
; ==> (5 5 5 5 5 5 5 5 5 5)

(times/list (lambda _ (+ 1 (random 5))) 10)
; ==> (4 2 2 4 4 1 5 3 1 3) (varies)

You can use for/list like this:

(define (times/list proc n)
  (for/list ([i n]) (proc)))

Using it:

> (times/list (λ () (random 5)) 10)
'(3 4 3 3 0 0 4 0 2 1)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!