Sitemap

Function Composition using Tuples

7 min readNov 22, 2016

--

I recently ran into a use case for composing functions using tuples. Since I often see functional programming articles covering basic concepts like function composition, but not a lot of them seem to cover this approach, I thought I would share my notes on it. If you’re new to function composition, here’s a great place to start.

JavaScript doesn’t really have tuples, let’s just get that right out in the open. So for the purposes of this article I will be using the term a bit loosely as a succinct way to describe how I’ll be using arrays to achieve the same effect. For those unfamiliar with the term, a tuple is an ordered list of a finite number of elements. Sounds suspiciously similar to the definition of an array, am I right? The key difference being the finite number of elements—whereas an array can vary in size. Just to illustrate, a 3-tuple would always have the following shape, regardless of its contents:

[element1, element2, element3]

For the sake of this article, say you have specific business rules that apply to types of users. Not every user is built the same, some need specific details pertaining to their user role, and so on. You have a series of functions that can augment a user with details needed on the user object, each one needs a user object to operate on and an object with the details to apply. Your data source comes from an API and you need to transform some of the structure or values to make the final user object useful for your app.

You could handle this with a function that builds an object, setting property values with function calls.

function configureUser(user, userOptions) {
return {
name: user.name
id: getId(userOptions),
role: getUserRole(userOptions),
etc: user.etc // you get the idea
}
}

The problem with implementations like this is they can be brittle and a pain to manage as your application grows, so you decided the solution that might best fit your situation is function composition. The only problem is each function needs to have a common input and output in order to be composed together successfully, in this case user and userOptions. This idea doesn’t work well with traditional examples of function composition.

The problem derives from the fact that functions can only return a single natural value. The following function, for example, would not behave how you might expect.

function notReally() {
return oneThing, anotherThing
}

In actuality, only the last value in the return statement would be returned.

The problem starts becoming clear when you consider the fact that composed functions typically operate on a single value since, as you saw above, functions can only return a single value. Composing together functions that each need to operate on two separate values can get pretty messy; for instance, you might at first think to apply the second value to each of the functions before composing them.

I’ll make use of Lodash’s partialRight to help illustrate.

const configureUser = compose(
_.partialRight(setId, userOptions),
_.partialRight(setUserRole, userOptions)
)
const modifiedUser = configureUser(user)

This approach is not ideal because you end up with a lot of boilerplate code when all you wanted was simple function composition. It also limits what the composed functions can do, because you lose the ability to pass a different userOptions object each step of the way—which could prove useful, depending on your situation.

So just to bring into perspective the problem at hand,

  • you want to compose functions together that operate on 2 inputs (with possibly additional option parameters)
  • you want to avoid messy boilerplate code
  • functions can only return a single value

Now, we can start solving this problem by using tuples in your composable functions. First, let’s take a look at what one of these functions might already look like, before you refactor it to use tuples.

function setId(s, o) {
const id = o.userId
return Object.assign({}, s, {id})
}
setId({name: 'Gazorpazorp'}, {userId: 42})
// => {name: 'Gazorpazorp', id: 42}

Similarly, the other functions you want to compose this with also require the two s and o inputs; s being the source object and o being an object containing values that need to be transformed before adding them to the source object. So these parameters are what you want made into a tuple. Imagine that you will be making the same changes to each of your functions as we go.

You may have already jumped ahead of me and assumed that the first thing you’re going to do is accept and return a tuple instead. Let’s go ahead and do that now, to see what that would look like.

function setId(dataTuple) {
// let's destructure that to make things easier
const [s, o] = dataTuple
const id = o.userId
return [Object.assign({}, s, {id}), o]
}
setId([{name: 'Gazorpazorp'}, {userId: 42}])
// => [{name: 'Gazorpazorp', id: 42}, {userId: 42}]

We’re off to a good start. Your functions can now accept a tuple and return a tuple. However, it’s a bit brittle and could definitely be improved. Personally, when I call the composed function, I would rather not have to explicitly write the initial tuple. Compare the following examples of the final composed function, which do you like better?

configureUser([user, userOptions])configureUser(user, userOptions)

So, you could refactor your functions even further, making them look something like the following—but wait, wasn’t the whole purpose of this exercise to avoid adding boilerplate?

function setId(maybeSource, maybeOptions, probablyId) {
if ([].concat(maybeSource).length < 2) {
var tuple = [maybeSource, maybeOptions]
var id = probablyId || maybeOptions.userId
} else {
var tuple = maybeSource
var id = maybeOptions || tuple[1].userId
}
return [Object.assign({}, maybeSource, {id}), tuple[1]]
}

Oof! That’s painful. I can barely understand that mess—and I’m the one who wrote it! Let’s not go down that road.

Get Kevin Lanni’s stories in your inbox

Join Medium for free to get updates from this writer.

You wanted to use tuples with function composition, but you were trying to avoid messy boilerplate code, so what now? Luckily, you can have your cake and eat it too…

To do just that, you’ll need to write a wrapper function that can transform incoming parameters into tuples automatically. This will help you to avoid all of the boilerplate mess both in your functions and in the composition.

Start by writing the basic functionality and we’ll improve it later.

function argsAsTuple(fn) {
return function(tuple, ...args) {
[].concat(tuple).length === 2 ?
fn(tuple, ...args) :
fn([tuple, args[0]], ...args.slice(1))
}
}

What argsAsTuple will do is take your target function fn and return the wrapper. When called, the wrapper will check the first argument’s length to see if it was a tuple, if everything looks good, it calls your function fn with the arguments. If not, it will create a tuple from the tuple variable and the first element from args and apply the rest of args to your function. This effectively makes passing a tuple to fn optional.

Now you can pass your functions to argsAsTuple to making calling it easier.

const configureUser = compose(
argsAsTuple(setId),
argsAsTuple(setUserRole)
)
configureUser(user, userOptions)// or if you really prefer writing the tuple out you can still do
configureUser([user, userOptions])

Let’s create one more helper just to streamline the process.

const tupler = (...fs) => fs.map(f => argsAsTuple(f))

This function will just apply argsAsTuple to all of the given functions, to eliminate that last bit of boilerplate.

Note: this could have been done elsewhere or abstracted, but I didn’t want to obfuscate this step for my later examples.

Great, now you can compose any number of this type of function together with zero boilerplate. If argsAsTuple will only ever be used with 2-tuples you can stop here, you’re done. However, I would argue that your shiny new argsAsTuple function could be useful in other parts of your application where maybe you need to work with tuples of different sizes.

It would be nice to be able to specify the tuple size, so let’s go ahead and improve argsAsTuple even further. Add a ln parameter to the function so you can define the tuple size. While you’re at it, give it a default size of 2.

function argsAsTuple(fn, ln = 2) {
return function(tuple, ...args) {
[].concat(tuple).length === ln ?
fn(tuple, ...args) :
fn([tuple, ...args.slice(0, ln - 1)], ...args.slice(ln - 1))
}
}

Much better, now this function is even more useful due to its flexibility, and we didn’t add any boilerplate to our function composition thanks to the default value of ln. Notice that when your function has to create the tuple it now has to slice from args because you don’t know what ln will be.

Looks great. You can leave it exactly as-is now, you don’t really want to add more functionality to it than that, so it doesn’t outgrow its responsibility. Though you could trim it down a bit more if you want to make full use of ES6 features like arrow functions. You could even employ a little trick with default parameters to predefine the ln — 1 expression. Here’s what your completed function now looks like.

const argsAsTuple = (fn, ln = 2, i = ln - 1) => (tuple, ...args) =>
[].concat(tuple).length === ln ?
fn(tuple, ...args) :
fn([tuple, ...args.slice(0, i)], ...args.slice(i))

Take one last look at your function composition and some example usage.

const tupler = (...fs) => fs.map(f => argsAsTuple(f))const configureUser = compose(tupler(
setId,
setUserRole,
([user]) => user // extract the user from the tuple at the end
))
// we can use our imaginations for setUserRoleconst user = {name: 'Gazorpazorp'}const gazorpazorp = configureUser(user, {userId: 2, roleId: 1})
// => {name: 'Gazorpazorp', id: 2, role: 'admin'}
const beeblebrox = configureUser({name: 'Zaphod'}, {
userId: 42,
roleId: 2
})
// => {name: 'Zaphod', id: 42, role: 'Galactic President'}

And there you have it: function composition using tuples. Even though JavaScript doesn’t have a tuple type, we can fake it with an array and get essentially the same benefits. By faking it, we can do cool things like using tuples in function composition.

Thanks for reading!

--

--

Kevin Lanni
Kevin Lanni

Written by Kevin Lanni

Programmer ◆ Web Developer ◆ Grower of Beards