Quantcast
Channel: First steps - JuliaLang
Viewing all articles
Browse latest Browse all 2795

Multiple dispatch usage with named arguments

$
0
0

@Rajesh_Talluri wrote:

Hi,
I am trying to write a function which has multiple arguments. The argument maf could be a single value or a vector of length p.

function simulate_data(; n::Int64 = 1000, p::Int64 = 5, maf = 0.3)

if length(maf) == 1    
        mnaf = fill(maf,p)   # make maf a vector of length p if only one value is specified
    elseif length(maf) == p
        mnaf = maf
    else
        error("maf argument is incorrect")
    end
rand.(Binomial.(1, mnaf), n, 1)
# other code
end

My understanding of multiple dispatch is to create two functions

function simulate_data(n::Int64, p::Int64, maf::Float64)
rand.(Binomial.(1, fill(maf,p) ), n, 1)
# other code
end

function simulate_data(n::Int64, p::Int64, maf::Array{Float64 ,1})
rand.(Binomial.(1, maf), n, 1)
# other code
end

This works. However, is this recommended? This is duplicating a lot of code, just to change a couple of lines of code (Assuming# other code does a lot of stuff), and the purpose of writing functions in the first place was to reduce duplication.

Does multiple dispatch not work with named arguments?

function simulate_data(; n::Int64 = 1000, p::Int64 = 5, maf::Float64 = 0.3)
rand.(Binomial.(1, fill(maf,p) ), n, 1)
# other code
end

function simulate_data(; n::Int64 = 1000, p::Int64 = 5, maf::Array{Float64 ,1} = [0.3,0.3,0.3,0.3,0.3])
rand.(Binomial.(1, maf), n, 1)
# other code
end

In this scenario the function gets overwritten. The first function with maf:: Float64 is not present.

Could someone please help me understand how to use multiple dispatch properly.

Thank You

Posts: 5

Participants: 4

Read full topic


Viewing all articles
Browse latest Browse all 2795

Latest Images

Trending Articles



Latest Images