Compose operator interacting with tuples


#1

My question is: how to best define functions so they compose nicely?

Here is the confusion. The following doesn’t work:

f(x) = x, x
g(a,b) = a+b

h = g∘f
h(1)

This produces a “MethodError: no method matching g(::Tuple{Int64,Int64})”
It works, however, if I add

g(xs) = g(xs...)

But I don’t really understand why. Much appreciated if someone can help me understand how to better define functions for composition.


#2

The return type of f is a tuple:

julia> typeof(f(1))
Tuple{Int64,Int64}

and g takes two arguments a and b. Therefore, g(f(1)) was undefined because you had not defined a g for one argument that does exactly what you implemented by adding another method to g: g(xs)=g(xs...) splats the tuple into a sequence of arguments.

You could do g((a,b))=a+b but i find your above solution more readable :slight_smile:

Cheers!