戸惑うなぁ
(fold + 0 '(2 2)) ;-> 4 (use srfi-43) (vector-fold + 0 '#(2 2)) ;-> 5 (vector-fold + 0 '#(2 2 2)) ;-> 9 (vector-fold + 0 '#(2 2 2 2)) ;-> 14 (vector-fold + 0 '#(2 2 2 2 2)) ;-> 20 (vector-fold + 0 '#(0 0)) ;-> 1 (vector-fold + 0 '#(0 0 0)) ;-> 3 (vector-fold + 0 '#(0 0 0 0)) ;-> 6 (vector-fold + 0 '#(0 0 0 0 0)) ;-> 10 (use gauche.collection) (fold + 0 '#(2 2)) ;-> 4
srfi-43のvector-foldだとindexも足し合わせているようだ.
(vector-fold kons knil vec1 vec2 ···) -> value
The fundamental vector iterator. Kons is iterated over each index in all of the vectors, stopping at the end of the shortest; kons is applied as (kons i state (vector-ref vec1 i) (vector-ref vec2 i) ···) where state is the current state value ― the current state value begins with knil, and becomes whatever kons returned at the respective iteration ―, and i is the current index.
成る程ちゃんと書いてある. 読まずに使おうとした俺が悪い.
(use srfi-43) (vector-fold (lambda (i s vi) (+ s (* vi vi))) 0 '#(2 2 2)) ;->12 (use gauche.collection) (fold (lambda (vi s) (+ (* vi vi) s)) 0 '#(2 2 2)) ;-> 12
こういうことね. 納得.
(use srfi-43) (vector-fold (lambda (i s vi) (+ s (if (= vi 1) i 0))) 0 '#(0 0 1 1 0 1 0 1 0 0)) ;0-10までの素数の和を求める. ;-> 17
これは使いやすい.