2016-05-21 125 views
1

您好,我嘗試在Julia語言中創建從Disct到Vector的轉換器方法。 但我收到錯誤,用我無法理解如何將Dict作爲參數傳遞給方法Julia

ERROR: TypeError: Tuple: in parameter, expected Type{T}, got Dict{AbstractString,Int64} 

我的代碼

type Family 
    name::UTF8String 
    value::Int 
end 

function convertToVector(a1::Dict{AbstractString, Int64}()) 
       A::Vector{Node} 
      for k in sort(collect(keys(a1))) 
       push!(A, Family(a1[k] , k)) 
       end 
      return A 
     end 

任何想法熱改convertToVector方法?

+0

也許只是一個錯字。它應該是'a1 :: Dict {AbstractString,Int64}'不'a1 :: Dict {AbstractString,Int64}()' – Gnimuc

+0

是的,工作,但我有另一個問題未定義在convertToVector –

回答

4

有在上面的代碼中的幾個錯別字,但我認爲這應該工作:

# No() after the type of a1 
# Also, see comment, better to parameterize function, use concrete type for Dict 
function convertToVector{T<:AbstractString}(a1::Dict{T, Int64}) 
    # This is how you create an empty vector to hold Family objects 
    A = Vector{Family}() 
    for k in sort(collect(keys(a1))) 
     # The values passed to the Family constructor were backwards 
     push!(A, Family(k, a1[k])) 
    end 
    A 
end 
+2

並使'convertToVector { T <:AbstractString}(a1 :: Dict {T,Int64})參數是必要的,我猜。 – Gnimuc

+1

這會好得多,我同意('Dict {AbstractString,Int64}'可以工作,但效率不高)。我只是試圖修復代碼中的錯誤;-) –

1

另一種方式(可能不是非常快):

julia> dict = Dict("fred" => 3, "jim" => 4) 
Dict{ASCIIString,Int64} with 2 entries: 
    "fred" => 3 
    "jim" => 4 

julia> Vector{Family}(map(f -> Family(f...), map(x -> collect(x), dict))) 
2-element Array{Family,1}: 
Family("fred",3) 
Family("jim",4) 

也許我已經使用過很多Lisp最近...

相關問題