0

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

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

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

输出必须类似于

(list 1 6)

4

2 回答 2

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))))

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

这只是一个一个地遍历列表,并进行三项检查

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

这会产生一个向后的列表,所以我们在最后反转它。

而已!:)

于 2013-08-16T15:19:43.657 回答
0

I'll give you some hints to solve this problem, it's much better if you reach a solution by your own means. Fill-in the blanks:

; 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

Notice that the idx parameter is necessary to keep track of the index we're currently over, starting at zero. When the recursion advances, you must advance both the input list and the index. Don't forget to test the procedure:

(position '(false A false false false false A false false false) 'A 0)
=> '(1 6)
于 2013-08-14T23:05:07.057 回答