Vim Script で、fold の続き

とりあえず、ここまでがんばった。
ついでに fold の引数順も変更。
特に意味はないけど。

[ソース]

" 各演算子を辞書型で定義
function! s:operator(op)
    let func = {"op" : a:op}
    function! func.call(a, b) dict
        return eval(a:a . self.op . a:b)
    endfunction
    return func
endfunction

" とりあえず、"+" と "-" だけ
let s:operators = {
    \ "+" : s:operator("+"),
    \ "-" : s:operator("-"),
    \ }

" 変数型を渡した場合エラーになるので、try〜cathc で無理やりチェック
function s:operators.get_impl(name) dict
    if has_key(self, a:name)
        return self[a:name]
    endif
    return a:name
endfunction

function! s:operators.get(name) dict
    try
        return self.get_impl(a:name)
    catch
        return a:name
    endtry
endfunction

" ---------------------------------------------------------
" forwardOp は、operators に登録されているものか、自分で定義した関数
function! s:foldl(forwardOp, state, list)
    let l:op = a:state
    let l:forwardOp = s:operators.get(a:forwardOp)
    for value in a:list
        let l:op = l:forwardOp.call(l:op, value)
    endfor
    return l:op
endfunction

" ---------------------------------------------------------
echo s:foldl("+", 1, [2, 3, 4])
echo s:foldl("-", 1, [2, 3, 4])

let first = {}
function! first.call(a, ...)
    return a:a
endfunction

echo s:foldl(first, 3, [3, 2, 5])

[出力]

10
-8
3

"+" なんかを辞書型に登録しておいて、対応している関数を呼び出しているだけですね。
operator 以外の場合は、そのまま呼び出しを行うので、自分で定義した関数も使用できますね。
あとは関数を呼び出しをどうにかしたいところ。
寝て起きたらきっとアイディアが浮かんでいるはず…!!