在 Julia 中提取参数类型 [英] Extracting parameter types in Julia

查看:15
本文介绍了在 Julia 中提取参数类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在 Julia 中编写了一个以 Dict{K,V} 作为参数的函数,然后创建 Array{K,1} 类型的数组代码>数组{V,1}.如何从 Dict 对象中提取类型 KV 以便我可以使用它们来创建数组?

Suppose I write a function in Julia that takes a Dict{K,V} as an argument, then creates arrays of type Array{K,1} and Array{V,1}. How can I extract the types K and V from the Dict object so that I can use them to create the arrays?

推荐答案

Sven 和 John 的回答都非常正确.如果不想像 John 的代码那样引入方法类型参数,可以使用 eltype 函数:

Sven and John's answers are both quite right. If you don't want to introduce method type parameters the way John's code does, you can use the eltype function:

julia> d = ["foo"=>1, "bar"=>2]
["foo"=>1,"bar"=>2]

julia> eltype(d)
(ASCIIString,Int64)

julia> eltype(d)[1]
ASCIIString (constructor with 1 method)

julia> eltype(d)[2]
Int64

julia> eltype(keys(d))
ASCIIString (constructor with 1 method)

julia> eltype(values(d))
Int64

如您所见,有几种方法可以给这只猫剥皮,但我认为 eltype(keys(d))eltype(values(d)) 是迄今为止最清晰的,因为 keysvalues 函数只返回不可变的视图对象,编译器足够聪明,实际上并不会创建任何对象.

As you can see, there are a few ways to skin this cat, but I think that eltype(keys(d)) and eltype(values(d)) are by far the clearest and since the keys and values functions just return immutable view objects, the compiler is clever enough that this doesn't actually create any objects.

这篇关于在 Julia 中提取参数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆