functional programming - Function that creates a list of all indexes where an element appears in a list -
i attempting write function (positions n l)
returns list of each index appears in l , n number given first element of l.
for example,
(positions 0 'a '(a b c d e a))
=> (0 3 6)
(positions 1 'a '(a b c d e a))
=> (1 4 7)
so far, have come (which isn't working correctly):
(define (positions n l) (cond ((null? l) '()) ((= (car l) a) (cons n (positions (+ n 1) (cdr l)))) (#t (positions (+ n 1) (cdr l)))))
try this:
(define (positions n l) (cond ((null? l) '()) ((equal? (car l) a) (cons n (positions (+ n 1) (cdr l)))) (else (positions (+ n 1) (cdr l)))))
the problem =
defined numbers. if you're that list contain symbols, use eq?
. otherwise use equal?
, general equality comparison , works many data types (numbers, symbols, booleans, etc.) also, use else
last condition, using #t
common lisp convention doesn't apply in scheme.
Comments
Post a Comment