2011-03-19 31 views
1

,所以我想從列表中的前指數:試圖從列表中得到一個元素的索引方案

(GET-指數「G(名單」 A「G」 T「X 'I' T 'G))

(2 7)

其中索引從1開始,從而' A是索引一個

我想上使用輔助功能,其中它採用ELT LST和索引 ex:(get-indices-helper el 1st index)

我也在考慮可能使用list-ref並將其切換爲使其以get索引方式工作,但我無法找到它的實際方案定義。

回答

3

編寫一個遞歸遞減輸入列表的函數,跟蹤它正在查看的元素的位置,併發出與cons匹配的索引。這真是微不足道的;我認爲這是你被定爲功課的問題?

; Walk down the list given in haystack, returning a list of indices at which 
; values equal? to needle appear. 
(define (get-indices needle haystack) 
    ; Loop along the haystack. 
    (define (loop rest-of-haystack index) 
    ; If the haystack is empty, return the empty list. 
    (if (null? rest-of-haystack) '() 
     ; Recurse to the next position in the list. 
     (let ((rest-of-indices (loop (cdr rest-of-haystack) (+ index 1)))) 
     (if (equal? (car rest-of-haystack) needle) 
      ; If haystack is here, emit the current index. 
      (cons index rest-of-indices) 
      ; Otherwise, return rest-of-indices. 
      rest-of-indices)))) 
    ; Run the loop defined above, from the beginning of haystack, with 
    ; the first element being assigned an index of 1. 
    (loop haystack 1)) 

測試這與GNU狡詐或使用MzScheme什麼:

(display (get-indices 'G (list 'A 'G 'T 'X 'I 'T 'G))) (newline) 
(display (get-indices 1 (list 1 1 1 2 1 3))) (newline) 

打印:

(2 7) 
(1 2 3 5) 

耶!

相關問題