4Clojure recently introduced me to Clojure’s curious
juxt function. From the official docs:
Takes a set of functions and returns a function that is the juxtaposition of those functions.
Makes a bit more sense once you see it in practice:
This alone is pretty neat, but it gets better. Jay Fields observed that
juxt has other interesting applications:
Implementing juxtapose in Ruby sounds like my idea of a good time. How might we go about this? We immediately run into a problem if we want to mimic the interface of Clojure’s juxt: The first example takes advantage of variadic functions that lack Ruby equivalents. Examining one of these functions, however, gives us a pretty strong hint:
This looks like a reduce function! Reduce is the most universal of functional programming’s three cornerstone functions (map, reduce and filter), so some sort of reduce-based solution should provide the desired results. In our first example, we pass three functions and get three results back, a pretty strong hint we should map our list of functions over the reduce operation. Our first implementation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Jackpot! This solution works and we even maintained the variadic interface from Clojure. The downside is that this solution requires us to recreate most of the functionality provided by
Array. While I rarely turn down the opportunity to write a stabby lambda, let’s assume we want to avoid this for the sake of argument. We can
send symbols to our list of arguments if we are willing to adapt the interface. One way to go about it:
1 2 3 4 5 6 7
This version of juxt brings a second meaningful improvement on top of being able to use
Enumerable: Now we can juxtapose methods that require a block alongside those where a block is optional:
I find this diversion so interesting because I only considered doing things like this in Ruby after I discovered Clojure. There is much to be learned about Ruby by exploring functional programming langugages.