Join – nifty little utility function

I have been watching Hardcore Functional Programming in Javascript in Pluralsight and it’s been really good so far (video is just a tiny bit over 6 hours). The video showed (among many other things) a rather neat way of combining two function paths that I of course had to try out on Hy too.

Note: in video, this utility function is called fork, but I chose to use join as it (in my opinion) describes better what’s happening.

I like building software from small, reusable components and have as small amount of boilerplate code as possible. Sometimes you want to define a new function in terms of two existing ones and pass same parameter to both of them. For example, in order to calculate average of items in a list:

=> (defn avg [coll]
...  (/ (sum coll) (len coll)))
=> (avg [1 2 3 4 5 6 7 8 9 10])
5.5

By all means, it’s not ugly or wordy or anything. Just a regular function doing calculation.

But lets define a utility function join that neatly joins two functions that are called with same parameter with the third one. And since we’re at it, define join to be curryable:

=> (import [toolz [curry]])
=> (with-decorator curry
...  (defn join [lastly f g x]
...    (lastly (f x) (g x))))

It has exactly the same pattern as in the avg function, so we can redefine avg differently now:

=> (def avg (join / sum len))
=> (avg [1 2 3 4 5 6 7 8 9 10])
5.5

Now the definition is much more concise and maybe even easier to read (if you know what join does, of course): “define avg to be division of sum and length of whatever is passed into it”.

How nifty is that?

pipes

building more functions

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s