问题
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