DrRacket:如何获取列表中值的位置

时间:2013-08-12 19:24:05

标签: scheme racket intermediate-language

我正在尝试获取中级学生语言列表中值的位置列表。

例如,我希望以下列表中的值“A”的位置列表

(list false A false false false false A false false false )

输出必须类似于

(list 1 6)

2 个答案:

答案 0 :(得分:1)

有一些我们可以很快理解的东西,第一个是你需要通过初始列表进行递归,第二个是你需要保留一个累加器列表,不知何故有一个关于你正在查看的第一个列表的元素的概念,所以我们也可以添加一个计数器。

所以,

; listsearch : (listof Any) Any -> (listof Int)
;   Searches a list for val and returns a list of indexes for occurrences of val in lst
;   (listsearch '(1 2 1 3 4 1) 1) => '(0 2 5)
(define (listsearch lst val) 
  (local [(define (helper lst acc counter)
            (cond [(empty? lst)             acc]
                  [(equal? val (first lst)) (helper (rest lst) 
                                                    (cons counter acc)
                                                    (add1 counter))]
                  [else                     (helper (rest lst) acc (add1 counter))]))]
    (reverse (helper lst empty 0))))

我添加了一个本地因为计数器应该存在,但我们希望实际的功能整洁,所以调用只需要一个列表和一个值。

这只是逐个浏览列表,并进行三次检查

  • 列表是空的吗?返回我累积的清单(基数为空)
  • 列表中的第一项是我的价值吗?重新开始,但将该值添加到我的累加器并将一个值添加到我的计数器
  • 列表中的第一项是别的吗?重新开始,但在我的柜台添加一个

这导致了一个向后的列表,所以我们在最后反转它。

就是这样! :)

答案 1 :(得分:0)

我会给你一些解决这个问题的提示,如果你通过自己的方式达成解决方案会好得多。填写空白:

; position procedure
;    lst: input list
;    ele: the searched element
;    idx: initial index, starts in 0
(define (position lst ele idx)
  (cond (<???>       ; if the input list is empty
         <???>)      ; then we're done, return the empty list
        (<???>       ; if the current element equals the one we're looking then
         (cons <???> ; build output list, cons the index where we found it
               (position <???> ele <???>))) ; and advance the recursion
        (else                               ; otherwise
         (position <???> ele <???>))))      ; just advance the recursion

请注意,idx参数对于跟踪我们当前所处的索引是必要的,从零开始。递归前进时,必须同时前进输入列表和索引。不要忘记测试程序:

(position '(false A false false false false A false false false) 'A 0)
=> '(1 6)
相关问题