I am learning scheme a bit and writing methods basically by first, writing that method in python (recursively) and then translating it into scheme. For example, here is an attempt at writing an list index position:
def idx(elem, l, n=0):
"Recursive routine for [1,2,3].index(2)"
if not l:
return -1
else:
return n if (l[0] == elem) else idx(elem, l[1:], n+1)
idx(2, [1,2,3])
# 1
Translating it:
(define (get-idx elem List n)
(if (= (length List) 0) -1
(if
(equal? (car List) elem)
n
(get-idx elem (cdr List) (+ n 1)))))
A few questions on this:
- How could I remove the need to pass the
n
(current index increment) to the function? Would I need to have a wrapper function around it or what's the usual way to do that? - Other than that, how can it be formatted/made cleaner?
I suppose one way to make it 'cleaner' might be to have it as:
(define (get-idx-internal elem List n)
(if (= (length List) 0) -1
(if (equal? (car List) elem) n
(get-idx-internal elem (cdr List) (+ n 1)))))
(define (get-idx elem List) (get-idx-internal elem List 0))
(display (get-idx 3 (list 1 2 3 4 5)))
; 2