How to create a list with n applications of a procedure

末鹿安然 提交于 2019-12-22 18:51:13

问题


My question is related to this one but in my case I would like to obtain a list with the results of n applications of a function whose output is not computable again with the previous result (picking randomly an element from a list, for example).

That is, it is not the composition of a function n times with itself but the n results shown together into a list.


回答1:


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)



回答2:


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)


来源:https://stackoverflow.com/questions/54024035/how-to-create-a-list-with-n-applications-of-a-procedure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!