I want to have a curried version of a function. So, I write the code as follows:
f(x::Int64, y::Int64) = x + y
f(x::Int64) = (y::Int64) -> f(x, y)
But I am not sure if Julia considers this an example of a type-unstable definition. On the face of it, one of the methods returns an anonymous function, while another returns an Int64
. Yet, when the curried version is applied, the final result is also an Int64
.
So, my questions are:
- Is this code type-stable?
- If not, is there a way to have a curried version of a function without writing type-unstable code?
Thanks in advance.
Yes, it is.
According to the official doc, you can investigate it by using the
@code_warntype
macro:The arguments of this function have the exact type
Int64
, and as we can see in theBody::Int64
, the inferred return type function isInt64
.Furthermore, we have
f(x)
which is based on the type-stable functionf(x, y)
:Here as well, there's not any unstable defined parameter type.
Look at the following as an example of an unstable-typed function:
If you try this in the REPL, you'll see the
Any
appears with a red color. Since we have theBody::Any
(Any
with the red color), we can conclude that the returned object by this function is a non-concrete type object. Because the compiler doesn't know what is thex
(Note that the input isX
). So the result can beAny
thing! So this function is type-unstable for (here, for integer inputs. Note that you should investigate the type-stability of your function by your desired input(s). E.g.,@code_warntype f(5)
and@code_warntype f(5.)
should be observed if I can pass itFloat64
orInt64
either).