20

関数である引数に型情報を追加できますか?

次の例を検討してください。

function f{T} (func, x::Int)
    output = Dict{Int, Any}()
    output[x] = func(x)
    return output
end 

Any辞書の値の型について言わなければならないのは好きではありません。私はむしろ次のことをしたいと思います:

function f{T} (func::Function{Int->T}, x::Int)
    output = Dict{Int, T}()
    output[x] = func(x)
    return output
end 

このような関数の型ヒントを提供できますか? 次のようなことを言いたい

f :: (Int -> T), Int -> Dict{Int, T}
4

2 に答える 2

1

これは主な質問への回答ではありませんが、問題の非常に醜い回避策です。AnyDict

function f(func, x::Int)
    T = code_typed(func, (Int,))[1].args[3].typ
    output = Dict{Int, T}()
    output[x] = func(x)
    return output
end

それはおそらく効率的ではなく、おそらく次のような単純なケース(匿名関数さえ含まない)でのみ機能します

>>> g(x) = x*2
>>> typeof(f(g, 1234))
Dict{Int64,Int64}

>>> h(x) = x > zero(x) ? x : nothing
>>> typeof(f(h, 1234))
Dict{Int64,Union(Int64,Nothing)}

編集:

これはよりうまく機能します:

function f(func, x::Int)
    [x => func(x)]
end

>>> dump( f(x->2x, 3) )
Dict{Int64,Int64} len 1
    3: Int64 6
于 2014-02-01T03:18:23.003 に答える