Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function signatures in julia

Tags:

julia

I am interested in understanding the actual difference, if any, between the following two function definitions

function foo(n::Integer)
    println("hello")
end

function foo{T<:Integer}(n::T)
    println("hello")
end

As far as I understand the second form triggers a new compilation every time the function is called for a new type T, but what actually happens in the first case? Is there any effect on performance associated to the first form?

Thanks

like image 332
Davide Avatar asked Jun 16 '15 19:06

Davide


1 Answers

Parameters on function arguments are for method disambiguation rather than performance. From the docs http://docs.julialang.org/en/latest/manual/style-guide/#avoid-writing-overly-specific-types

The key thing to realize is that there is no performance penalty to defining only the general addone(x) = x + one(x), because Julia will automatically compile specialized versions as needed. For example, the first time you call addone(12), Julia will automatically compile a specialized addone function for x::Int arguments, with the call to one() replaced by its inlined value 1. Therefore, the first three definitions of addone above are completely redundant.

EDIT to address comment:

The difference between the two signatures is really only apparent when there are more than one argument

Consider the two functions:

julia> function foo(n::Integer, m::Integer)
           println(typeof(n), typeof(m))
       end

julia> function foo{T<:Integer}(n::T, m::T)
           println("Parameterized: ", typeof(n), typeof(m))
       end

In the first function n and m must both be integers but they do not have to be the same subtype of integer. In the second function, both m and n must be the same subtype

julia> foo(1, 2)
Parameterized: Int64Int64

julia> foo(1, Int32(1))
Int64Int32
like image 89
ptb Avatar answered Sep 19 '22 00:09

ptb