简体   繁体   English

在球拍中定义mylength函数

[英]define mylength function in racket

I'm trying to figure out how to define a length function in racket. 我试图弄清楚如何在球拍中定义一个长度函数。 Here's my code: 这是我的代码:

(define mylength
  (lambda (lst)
    (cond
     ((null? lst) 0)
     (else (+ 1 (mylength (cdr lst))))
     )))

If I try (mylength '(1 2 3)) the result is 3. When I try (mylength '(1 (2 3) 4)) the result still is 3. But the result should be 4. How do I do that? 如果我尝试(mylength '(1 2 3)) ,结果是3。当我尝试(mylength '(1 (2 3) 4)) ,结果仍然是3。但是结果应该是4。我该怎么做? in Racket 在球拍中

If you want to count nested elements separately, you need to recurse into (car lst) as well. 如果要分别计算嵌套元素,则还需要递归到(car lst)

(define mylength
  (lambda (lst)
    (cond
     ((null? lst) 0)
     ((atom? lst) 1)
     (else (+ (mylength (car lst))
              (mylength (cdr lst))))
     )))

Note that this means that a nested empty list doesn't add to the length. 请注意,这意味着嵌套的空列表不会增加长度。

(mylength '(1 () 3))

will be 2 , not 3 . 将为2 ,而不是3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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