Just for fun: map as ‘higher-order function’ in bash

On The Balcony

Defined recursively, of course:

map () { 
  if [ $# -le 1 ]; then 
    return 
  else 
    local f=$1 
    local x=$2 
    shift 2 
    local xs=$@ 

    $f $x 

    map "$f" $xs 
  fi 
}

I’m not going to explain everything, but note the ‘local’ commands to keep everything in function scope (to prevent strange bugs) and the quotes around $f in the recursive call to prevent a ‘function call’ of multiple words from being split.

Now you can do some completely nonsensical things, for which you really don’t need map, such as:

$ map touch aap noot mies

But also slightly more useful things such as

$ map "echo foo" aap noot mies 
foo aap 
foo noot 
foo mies 

$ map "echo file:" `ls` 
file: aap 
file: noot 
file: mies

To open up some more possibilities, I also defined a ‘rota’ function, with rotates the arguments of a command such that…

View original post 124 more words

About isomorphismes

Argonaut: someone engaged in a dangerous but potentially rewarding adventure.
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s