Created
March 13, 2011 13:44
-
-
Save t9md/868100 to your computer and use it in GitHub Desktop.
vimscript でカリー化
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
" Utility function"{{{ | |
fun! Echo(e) | |
echo a:e | |
endfun | |
fun! Header(num) | |
echo "\n" . a:num . "\n" | |
endfun | |
command! -nargs=* H :call Header(<f-args>)"}}} | |
function! Curry(...)"{{{ | |
let args = deepcopy(a:000) | |
let o = {} | |
let o._fun = remove(args, 0) | |
let o._args = args | |
function! o.bind(obj) | |
let self._obj = a:obj | |
return self | |
endfunction | |
function! o.call(...) | |
return call(self._fun, self._args + a:000, get(self, '_obj', {})) | |
endfunction | |
return o | |
endfunction"}}} | |
function! s:each(lis, fun) | |
for e in a:lis | |
call a:fun(e) | |
endfor | |
endfunction | |
let lis = range(5) | |
unlet! val | |
H 0.0)---- | |
call s:each(lis, function('Echo')) | |
H 0.1)---- | |
call call(function('s:each'), [lis, function('Echo')]) | |
H 1)---- | |
call call(function('s:each'), [lis, function('Echo')]) | |
H 2)---- | |
call Curry(function('s:each')).call(lis, function('Echo')) | |
H 3)---- | |
call Curry(function('s:each'), lis).call(function('Echo')) | |
H 4)---- | |
call Curry(function('s:each'), lis, function('Echo')).call() | |
echo '---------------------------------------' | |
" Result: {{{ | |
" 0.0)---- | |
" 0 | |
" 1 | |
" 2 | |
" 3 | |
" 4 | |
" 0.1)---- | |
" 0 | |
" 1 | |
" 2 | |
" 3 | |
" 4 | |
" 1)---- | |
" 0 | |
" 1 | |
" 2 | |
" 3 | |
" 4 | |
" 2)---- | |
" 0 | |
" 1 | |
" 2 | |
" 3 | |
" 4 | |
" 3)---- | |
" 0 | |
" 1 | |
" 2 | |
" 3 | |
" 4 | |
" 4)---- | |
" 0 | |
" 1 | |
" 2 | |
" 3 | |
" 4 | |
"}}} | |
" String object"{{{ | |
let s = {} | |
function! s.new(str) | |
let o = deepcopy(self) | |
let o._data = a:str | |
return o | |
endfunction | |
function! s.upcase() | |
return toupper(self._data) | |
endfunction | |
function! s.tolower() | |
return tolower(self._data) | |
endfunction | |
let String = s | |
"}}} | |
echo String.new('abc').upcase() |" => "ABC" | |
echo call(String.upcase, [], String.new("abcdefg")) |" => "ABCDEFG" | |
let upcase = Curry(String.upcase) | |
let lower_string = String.new('lower string') | |
call upcase.bind(lower_string) | |
echo upcase.call() |" => "LOWER STRING" | |
echo Curry(String.upcase).bind(String.new("lower")).call() |" => "LOWER" | |
echo Curry(String.tolower).bind(String.new("UPPER")).call()|" => "upper" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment