Cercando di ottenere gli indici di un elemento da un elenco in schema
Domanda
Quindi sto cercando di ottenere gli indici da un elenco Ex:
(Get-Indices 'G (List' A 'G' T 'x' I 'T' G))
(2 7)
dove l'indice inizia da 1 quindi a è indice uno
Stavo pensando di usare una funzione helper in cui ci vuole un ELT LST e un indice Ex: (Get-Indices-Helper EL LST INDICE)
Stavo anche pensando di usare eventualmente Elenco Ref e come cambiarlo per farlo funzionare nel modo in cui gli indici di Get, tuttavia non sono riuscito a trovare la definizione effettiva dello schema per esso.
Soluzione
Scrivi una funzione che ricorda l'elenco di input, tenendo traccia della posizione dell'elemento con cui sta guardando e emettendo gli indici di corrispondenza con cons
. Questo è davvero banale; Presumo che sia una domanda che sei stato messo come compiti?
; 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))
Testare questo con Gnu Guile o Mzscheme o qualcosa del genere:
(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)
Stampe:
(2 7)
(1 2 3 5)
Sìì!