LoginSignup
2
2

More than 5 years have passed since last update.

sort() 関数の注意点

Posted at

Vim script には標準でリストをソートする sort() 関数があります.

echo sort([3, 1, 4, 2]) " => [1,2,3,4]

しかしこれは注意が必要で,sort() はデフォルトでは文字列的に要素を比較してソートを行うため,数値的な比較でのソートを期待している場合,正しくソートされません.

echo sort([10, 1, 2, 100]) " => [1, 10, 100, 2]

数値的にソートするには,比較用の関数を作って渡す必要があります.

" 比較用の関数 lhs のほうが大きければ正数,小さければ負数,lhs と rhs が等しければ 0 を返す
function! s:compare(lhs, rhs)
    return a:lhs - a:rhs
endfunction

echo sort([10, 1, 2, 100], 's:compare') " => [1, 2, 10, 100]

詳しくは :help sort() に書かれています.

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2