Julia 中是否有一种方法可以通过类型注释指定函数参数可以采用一组值中的一个?例如,假设我有一个函数 foo
,它接受单个参数
function foo(x::String)
print(x)
end
参数x
只能是字符串。有没有办法在函数签名中进一步限制它,使其只能是字符串“right”、“left”或“center”之一?
最佳答案
在 Julia 中,座右铭应该是“有一种类型!”。 处理此问题的一种方法是创建一个带有构造函数的类型,该构造函数仅允许您想要的值(并且可能以更有效的方式存储它们)。 这是一个例子:
const directions = ["left", "right", "center"]
immutable MyDirection
Direction::Int8
function MyDirection(str::AbstractString)
i = findnext(directions, str, 1)
i == 0 && throw(ArgumentError("Invalid direction string"))
return new(i)
end
end
Base.show(io::IO, x::MyDirection) = print(io, string("MyDirection(\"",directions[x.Direction],"\")"))
function foo(x::MyDirection)
println(x)
end
function foo(str::AbstractString)
x = MyDirection(str)
println(x)
end
test = MyDirection("left")
foo(test)
foo("right")
注意:我的示例是用 Julia 0.4 编写的!
编辑: 另一种方法是使用符号,例如 :left、:right 和 :center, 而不是字符串。 它们的优点是可以被保留(这样就可以简单地通过比较它们的地址来进行比较),并且它们也可以直接用于类型参数。
例如:
immutable MyDirection{Symbol} ; end
function MyDirection(dir::Symbol)
dir in (:left, :right, :center) || error("invalid direction")
MyDirection{dir}()
end
MyDirection(dir::AbstractString) = MyDirection(symbol(dir))
这将使您可以执行以下操作: x = MyDirection("左") 这将创建一个 MyDirection{:left} 类型的不可变对象(immutable对象)。
关于julia - 将参数限制为 Julia 函数签名中的一组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31893278/