简体   繁体   中英

Racket - How to assign a length to a list

I was wondering, in racket, how would you assign a certain length to a list.

This is the code I want to run:

(check-expect (length a-list-of-length-104) 104)

How would you go about this without actually inputting 104 elements into the list?

This is my end goal:

(define (random-element a-list)
(list-ref a-list (random (length a-list))))

(random-element a-list-of-length-104)
(random-element a-list-of-length-104)
(random-element a-list-of-length-104)

It should produce a different output everytime.

The length of a list is the number of elements it contains. So you can't "assign a length to a list".

However you can create a list with a certain number of elements, more conveniently. Assuming #lang racket , you can use build-list .

To build a list consisting of the integers from 0 through 103:

(build-list 104 values)

To build a list consisting of 104 of random real numbers:

(build-list 104 (lambda _ (random)))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM