I'm trying to do a recursive function that gets a list of string-int pairs + a string named prefix, and using function named "starts-with" it sums up all the ints whose begininng match the prefix. Problem is, I can never get the list to go forward, it gets stuck at the beginning and then program crashes.
(define (sum-of-pairs-start-with prefix ls)
( let*( (prefix2 (string->list prefix))
(str2 (string->list (car (car ls)))))
(cond((null? str2) 0)
( (starts-with prefix (car(car ls)))
(+ cdr(car ls) (sum-of-pairs-start-with prefix (cdr ls))) )
(else sum-of-pairs-start-with prefix (cdr ls))) ) )
I work with input:
(sum-of-pairs-start-with "a" (list (cons "a" 1) (cons "b" 2) (cons "aa" 33) (cons "ca" 4))) ;; =34
but once i get to the second pair in the list ("b" 2) it goes to the else condition as expected, but then ls gets back up one line to origin (with the previous value) instead of going forward to next value ("aa" 33). I 'm new to scheme and I dont get why that happens, it's frustrating
(list (+ 1 2))
and(list + 1 2)
. The compiler or interpreter will not complain about the second one because it is a perfectly legal expression. It is also almost certainly not what you want. – Michael Vehrscdr
,(car ls)
, and the recursive result.) – molbdnilo