Reduce is a function or method that is used to take the values in an array or a list and apply a function to successive members of the list to produce (or reduce them to), a single value.



Task

Show how reduce (or foldl or foldr etc), work (or would be implemented) in your language.



See also

 Wikipedia article:   Fold
 Wikipedia article:   Catamorphism


define catbuf $10
define catbuf_temp $12
 
ldx #0
ramloop:
txa
sta $00,x
inx
cpx #$10
bne ramloop	
;load zero page addresses $00-$0f with values equal
;to that address
 
 
ldx #0		;zero X
loop_cata:
lda $00,x	;load the zeroth element
clc
adc $01,x	;add the first to it.
inx		
inx		;inx twice. Otherwise the same element
		;would get added twice
sta catbuf_temp ;store in temp ram
lda catbuf	
clc
adc catbuf_temp ;add to previously stored value
sta catbuf	;store in result
cpx #$10	;is the range over?
bne loop_cata	;if not, loop again
 
ldx #$00
lda catbuf
sta $00,x	
;store the sum in the zeroth entry of the range
 
inx
lda #$00
 
;now clear the rest of zeropage, leaving only the sum
 
clear_ram:
sta $00,x
inx
cpx #$ff
bne clear_ram