tbeason
February 26, 2020, 6:45pm
1
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?
pbayer
February 26, 2020, 6:53pm
2
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))
rdeits
February 26, 2020, 6:54pm
3
How about:
hfun(args....) = exp(gfun(args...))
?
6 Likes
tbeason
February 26, 2020, 6:54pm
4
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
tbeason
February 26, 2020, 7:03pm
5
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.
rdeits
February 26, 2020, 8:08pm
7
BTW, doing const hfun = ...
will give better performance if hfun
is a global variable.
2 Likes