Composition of functions and method dispatch

I have a number of functions like so

gfun(m::Type1,t) 
gfun(m::Type2,t)
gfun(m::Type3,x,t)

In every case, I would like to define a different function, call it hfun, that takes the same arguments and just composes a simple function, maybe exp, with the appropriate gfun (based on the arguments supplied).

hfun(m::Type1,t) = exp(gfun(m::Type1,t) )
hfun(m::Type2,t) = exp(gfun(m::Type2,t) )
hfun(m::Type3,x,t) = exp(gfun(m::Type3,x,t))

How do I define a “generic” hfun one time, rather than do it as I have written it?

hfun(m::T, t) where {T<:Union{Type1,Type2,Type2}} = exp(gfun(m,t))
hfun(m:Type3,x,t) = exp(gfun(m,x,t))

Yet more elegant: if you have super type for Type1,Type2..., then you can define

hfun(m::T, t) where {T<:MySuperType} = exp(gfun(m,t))

How about:

hfun(args....) = exp(gfun(args...))

?

6 Likes

m has a supertype but note that the number of arguments changes based on its type as well. That is really what is tripping me up.

1 Like

Aha. I guess I didn’t think about splatting all of the function arguments. I will give that a shot!

The MWE can also be handled with the composition operator:

hfun = exp ∘ gfun

In this case gfun will be a variable and not a function which may or may not make a difference in your case.

BTW, doing const hfun = ... will give better performance if hfun is a global variable.

2 Likes