Return a specific type for anonymous functions

Hello,

Im writing a function for add edge in a graph that takes a function as parameter, I’d like to ensure that function return a specified type E. How do I do it?

code:

function addedge!(G::DictGraph{V,E}, source::V, target::V; weightfunction::Function = (x,y) -> 1.0) :: Nothing where {V,E}
    !haskey(G.vvwr, source) && addvertex!(G, source)
    !haskey(G.vvwr, target)  && addvertex!(G, target)
    push!(G[source], target => weight)
    !G.isdirected && push!(G[target], source => weight)
    G.numedges += 1
    nothing
end

I think this solve for now

function addedge!(G::DictGraph{V,E}, source::V, target::V, args...; weightfunction::Function = (_...) -> 1.0)::Nothing where {V,E}
.
.
.
...push!(G[target], source => weightfunction(args...))

Why would you like to do this? It is something that is tricky or impossible to ensure using the type system, unless you use some kind of wrapper.

Generally I would suggest that you either check the type of arguments, or simply convert to the desired type. This is generally a low-cost operation and would make your code more generic.

1 Like