您的位置:首页 > Web前端

the Differences of Fold-left and Fold-right

2009-08-08 14:48 369 查看
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)))))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: