Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining one function for inputs of many types in Julia

Tags:

types

julia

Setup: I have a function in Julia that takes two inputs, x and y. Both inputs are arrays of the same type, where that type can be any number type, Date, DateTime, or String. Note, the contents of the function are identical regardless of any of the above element types of the input arrays, so I don't want to write the function out more than once. Currently, I have the function defined like this:

function MyFunc{T<:Number}(x::Array{T, 1}, y::Array{T, 1})

Obviously, this takes care of the numbers case, but not Date, DateTime, or String.

Question: What would be best practice in Julia for writing the first line of the function to accommodate these other types? Note, performance is important.

My Attempt: I could try something like:

function MyFunc{T<:Number}(x::Union(Array{T, 1}, Array{Date, 1}, Array{DateTime, 1}, Array{String, 1}) y::Union(Array{T, 1}, Array{Date, 1}, Array{DateTime, 1}, Array{String, 1}))

but this feels clumsy (or maybe it isn't?).

Links: I guess this is fairly closely related to another of my Stack Overflow questions on Julia that can be found here.

like image 909
Colin T Bowers Avatar asked Sep 30 '22 07:09

Colin T Bowers


People also ask

How do you define a function Julia?

A function in Julia is an object that takes a tuple of arguments and maps it to a return value. A function can be pure mathematical or can alter the state of another object in the program.

How do you take an array as input in Julia?

An Array in Julia can be created with the use of a pre-defined keyword Array() or by simply writing array elements within square brackets([]). There are different ways of creating different types of arrays.

How do you define a type of variable in Julia?

Declaring and Initializing Variables: This can be done by simply assigning a value to the named variable. variable_name = value. These variable values can be of any datatype: String, Integer, float, array, etc. as per user needs. Julia will assign the datatype automatically to the variable.

What is multiple dispatch in Julia?

Using all of a function's arguments to choose which method should be invoked, rather than just the first, is known as multiple dispatch.


1 Answers

The answer would be to use a Union, i.e.

function MyFunc{T<:Union{Number,Date,DateTime,String}}(x::Array{T, 1}, y::Array{T, 1})
    @show T
end

...

julia> MyFunc([1.0],[2.0])
T => Float64

julia> MyFunc(["Foo"],["Bar"])
T => ASCIIString

(using Julia 0.6.4 syntax...see the stable documentation for current syntax)

like image 65
IainDunning Avatar answered Oct 05 '22 07:10

IainDunning