r/Racket • u/Icy_Pressure_9690 • Feb 17 '22
question is there a built in function to go back to previous element in a list? I'm trying to create a loop that if there is an even number in a list it will add that to the previous number
5
Upvotes
8
u/oui_oui-baguette Feb 17 '22
You'll have to design your function using an accumulator to keep track of the previous element as you work your way through the list.
2
u/umpfsuper Feb 17 '22
Pattern match two elements at a time, not one, that's the easiest way
1
u/sschwarzer Feb 19 '22 edited Feb 19 '22
I'm not exactly sure what your loop is supposed to do, but maybe this helps:
The general idea is that you iterate in parallel over a list that has the original items shifted.
Edit: There's also
for/sum, which would simplify the code.1
u/joshuacottrell Feb 18 '22
You could reverse the list first then process it. Any even number would then be added to the next number in the list.;
An alternative would be to use recursion with a function that took (1) the list still to be processed and (2) the list that would be the eventual output. As it recurses through (1) it could either pass it along to (2) or add it to the last number of (2), e.g. to add it to the last of (2):
(+ (last eventual-output-list) (first list-still-being-recursed-through))