[英]In Racket how do i find the length of a list using struct instead of just using only higher-order functions or recursion
I'm pretty bad at understanding data structures in Racket right now so I'm currently working on a question where all I have to do is find the length of the list. 我现在很难理解Racket中的数据结构,因此我目前正在研究一个问题,我所要做的就是找到列表的长度。
I understand there are many ways to find the length of a list using recursion and foldr and map but I'm trying to find the length of a list a specific way right now. 我知道有很多方法可以使用递归,文件夹和映射来查找列表的长度,但是我现在正在尝试以特定的方式查找列表的长度。
Here are the details of the question; 这是问题的细节;
For this question, use the following data definition: 对于此问题,请使用以下数据定义:
(define-struct ls (first rest)) (定义结构ls(第一休息))
;; ;; a Ls is either
Ls要么是
;; ;; '(), or
'(), 要么
;; ;; (make-ls first rest) where first is an Int and rest is a Ls.
(make-ls first rest),其中first是Int,rest是Ls。
Keep in mind that since the structure is named ls, and its fields are named first and rest,you will access these fields using ls-first and ls-rest. 请记住,由于该结构的名称为ls,并且其字段的名称分别为first和rest,因此您将使用ls-first和ls-rest访问这些字段。
Here is the question 这是问题
Length. 长度。 Write a function (ls-length L) that consumes a Ls and returns the number of values in it.
编写一个使用Ls并返回其中值个数的函数(ls长度L)。
For example, (check-expect (ls-length (make-ls 5 (make-ls 7 (make-ls 11 '())))) 3) 例如,(check-expect(ls-length(make-ls 5(make-ls 7(make-ls 11'()))))3)
Here's a common way to find the length 这是找到长度的常用方法
(define (length lst)
(cond
[(empty? lst) 0]
[(cons? lst) (+ 1 (length (rest lst)))]))
I however want the question solved using 但是我想使用
(define-struct ls (first rest))
This is what I have so far but I know that this code seems very wrong, I feel my base case should be correct though. 到目前为止,这是我所拥有的,但是我知道这段代码似乎非常错误,不过我觉得我的基本情况应该是正确的。
(define (ls-length L)
(cond
[(empty? L) 0]
[(cons? (ls-first (first L))) (+ 1 (length (rest (ls-rest))))]))
You have to remember that you can't use cons?
您必须记住您不能使用
cons?
, rest
and first
on the new data structure, only empty?
,
rest
和first
对新的数据结构,只能empty?
, ls-first
and ls-rest
are allowed. 允许使用
ls-first
和ls-rest
。 The conditions are quite simple: the list is either empty or not empty, we don't really need cons?
条件非常简单:列表为空或不为空,我们真的不需要
cons?
. 。 Also, be careful when calling the recursion, the procedure is called
ls-length
, not length
: 另外,在调用递归时要小心,该过程称为
ls-length
,而不是length
:
(define (ls-length lst)
(cond
[(empty? lst) 0]
[else (+ 1 (ls-length (ls-rest lst)))]))
Compare the above with the well-known length
implementation: 将上面的代码与著名的
length
实现进行比较:
(define (length lst)
(cond
[(empty? lst) 0]
[else (+ 1 (length (rest lst)))]))
You see what happened? 你看到发生了什么事吗? we only had to replace
length
with ls-length
, and rest
with ls-rest
. 我们只需要替换
length
与ls-length
,和rest
用ls-rest
。 So simple! 很简单!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.