Skip to content

Instantly share code, notes, and snippets.

@tyru
Created January 19, 2010 13:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tyru/280926 to your computer and use it in GitHub Desktop.
Save tyru/280926 to your computer and use it in GitHub Desktop.
let s:expr = ''
func! s:sort_dummy_func(a, b)
let [a, b] = [a:a, a:b]
return eval(s:expr)
endfunc
" Perl's cmp, <=> operator like util function.
func! s:cmp(a, b)
return a:a ==# a:b ? 0 : a:a > a:b ? 1 : -1
endfunc
func! s:sort_by(list, expr)
let s:expr = a:expr
return sort(copy(a:list), 's:sort_dummy_func')
endfunc
let list = [4,4,6,2,1,2,34,4,56,6,6,3,2,1,7,8,45]
" sort by number.
echo s:sort_by(list, 's:cmp(a + 0, b + 0)')
" sort by string.
echo s:sort_by(list, 's:cmp(a . "",b . "")')
" 実行結果:
" [1, 1, 2, 2, 2, 3, 4, 4, 4, 6, 6, 6, 7, 8, 34, 45, 56]
" [1, 1, 2, 2, 2, 3, 34, 4, 4, 4, 45, 56, 6, 6, 6, 7, 8]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment