[英]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? 如果没有将104个元素输入到列表中,您将如何解决这个问题?
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
. 假设
#lang racket
,您可以使用build-list
。
To build a list consisting of the integers from 0 through 103: 要构建一个由0到103之间的整数组成的列表:
(build-list 104 values)
To build a list consisting of 104 of random real
numbers: 要构建一个由104个随机
real
数组成的列表:
(build-list 104 (lambda _ (random)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.