the Differences of Fold-left and Fold-right

Fold-left and Fold-right are two frequently used procedures when processing a list. They have the same declarations, but they have different implementations.

 

The declarations of Fold-left and Fold-right are followed. They combines all of the elements of the-list using the binary operation procedure. If the procedure obeys the associative-law, the fold-right and fold-left will get the same result. If (procedure a (procedure b c)) is equivalent to (procedure (procedure a b) c), then we can say the procedure obeys the associative-law. 

 

fold-right procedure initial the-list fold-left procedure initial the-list

 

Even though fold-left and fold-right behave the same in some cases, the internal calculating process are not the same for such cases. We should know the difference. In essence, fold-left is a iterative process, whereas fold-right is a recursive process.

 

The mimic implementations for fold-left and fold-right are followed. It is not difficult to make the conclusion.

 

(define (fold-left op initial sequence) (define (iter result rest) (if (null? rest) result (iter (op result (car rest)) (cdr rest)))) (iter initial sequence)) (define (fold-right2 op initial sequence) (if (null? sequence) initial (op (car sequence) (fold-right2 op initial (cdr sequence)))))

 

你可能感兴趣的:(c,REST,processing)