list-ref:索引对于列表Racket-EOPL来说太大了

时间:2013-11-19 04:11:23

标签: recursion scheme racket

我在使用list-ref时出现问题。

有没有办法使用list-ref来获取未知列表的大小?

 (... (if (number? (deref(+ array-ref index)))
          (array-len array-ref (+ index 1))
  0) )

#|(define(deref ref)   (list-ref the-store ref)) |#

2 个答案:

答案 0 :(得分:3)

如果您希望列表的尺寸使用length,而不是list-ref。例如,在这样的列表中:

(define lst '(1 2 3 4 5))

...有效索引介于0和列表length之间减一:

(list-ref lst 0)
=> 1

(list-ref lst (- (length lst) 1))
=> 5

然而:在Scheme中编写依赖于列表中元素的索引的代码是不常见的,这就是你如何使用数组来思考类C语言的解决方案,但是Scheme列表是不同的,通常你使用递归遍历列表 - 忘记索引!

答案 1 :(得分:0)

如果我理解正确,列表是列表,例如:

(define lst '((a b c)
              (1 "hi")
              ((lambda(x)(+ 5 x)) 42 'a (14 7 12))
              ("hello" " world")))

获取元素大小的快速而肮脏的方法是

 (define third-of-a-size (third (map length lst)))