2010/07/21

fold with index : fold/index

でっち上げるとしたらこんな感じでしょうか。
;; fold with index
(define (fold/index proc init ls . lss)
(let1 idx 0
(apply fold (lambda args
(begin0
(apply proc (append args (list idx)))
(set! idx (+ idx 1))))
init (cons ls lss))))
(fold/index (lambda (e acc idx)
(acons idx e acc))
'() '(a b c d e))
;; ((4 . e) (3 . d) (2 . c) (1 . b) (0 . a))
(fold/index (lambda (e1 e2 acc idx)
(acons e1 (cons e2 idx) acc))
'() '(a b c d e)'(f g h i j k))
;; ((e j . 4) (d i . 3) (c h . 2) (b g . 1) (a f . 0))
;; fold-right with index
(use srfi-1)
(define (fold-right/index proc init ls . lss)
(let1 idx (- (length ls) 1)
(apply fold-right (lambda args
(begin0
(apply proc (append args (list idx)))
(set! idx (- idx 1))))
init (cons ls lss))))
view raw index.scm hosted with ❤ by GitHub

追記

書かなくてもありました。

プログラミングGauche

0 件のコメント:

コメントを投稿