O'Reilly logo

Mastering Vim by Ruslan Osipov

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Map and filter

Vimscript supports map and filter—higher-order functions (aka functions that operate on functions). Both of these functions take either a list or a dictionary as a first argument, and a function as a second.

For instance, if we wanted to filter out every animal name that is not proper, we would write a filter function:


function IsProperName(name)  if a:name =~? '\(Mr\|Miss\) .\+'    return 1  endif  return 0endfunction

IsProperName will return 1 (true) if the name starts with Mr or Miss (which is, as we know, a proper form to address an animal), and 0 (false) otherwise.

Now, given the following dictionary:

let animal_names = {  \ 'cat': 'Miss Cattington',  \ 'dog': 'Mr Dogson',  \ 'parrot': 'Polly'  \ }

We will write a filter function ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required