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

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

问题描述

假设我在Julia中编写了一个函数,该函数将Dict{K,V}作为参数,然后创建了Array{K,1}Array{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天全站免登陆