在vimscript中对数字进行排序

时间:2014-12-01 11:03:37

标签: sorting vim

尝试使用vimscript并阅读精彩的Learn Vimscript the Hard Way(LVTHW),我意识到Vim并没有按照我想要的方式对数字进行排序。

例如来自LVTHW

的此功能
function! Sorted(l)
    let new_list = deepcopy(a:l)
    call sort(new_list)
    return new_list
endfunction
当我用Sorted([3, 1, 11, 2])打电话给我时,我感到很惊讶:

它返回了[1, 11, 2, 3]

我认为Vim按字母顺序对这些数字进行排序。但我希望该函数能够返回natural order中的数字: [1, 2, 3, 11]

我如何说服Vim(7.4)这样做?

2 个答案:

答案 0 :(得分:0)

诀窍是传递Vim​​的sort比较器函数,在我的情况下我称之为NaturalOrder

" Sorts numbers in ascending order.
" Examples:
" [2, 3, 1, 11, 2] --> [1, 2, 2, 3, 11]
" ['2', '1', '10','-1'] --> [-1, 1, 2, 10]
function! Sorted(list)
  " Make sure the list consists of numbers (and not strings)
  " This also ensures that the original list is not modified
  let nrs= ToNrs(a:list)
  let sortedList = sort(nrs, "NaturalOrder")
  echo sortedList
  return sortedList
endfunction

" Comparator function for natural ordering of numbers
function! NaturalOrder(firstNr, secondNr)
  if a:firstNr < a:secondNr
    return -1
  elseif a:firstNr > a:secondNr
    return 1
  else 
    return 0
  endif
endfunction

" Coerces every element of a list to a number. Returns a new list without
" modifying the original list.
function! ToNrs(list)
  let nrs = []
  for elem in a:list
    let nr = 0 + elem
    call add(nrs, nr)
  endfor
  return nrs
endfunction

答案 1 :(得分:0)

如果您已阅读sort()函数的帮助文档,则会看到您可以提供n{func}参数以让排序进行数字排序:

示例:

:echo sort([3,1,11,2],'n')
[1, 2, 3, 11]