在Julia中是否有一种方法可以指定函数参数可以通过类型注释获取一组值中的一个?例如,假设我有foo一个接受单个参数的函数
function foo(x::String)
print(x)
end
Run Code Online (Sandbox Code Playgroud)
参数x只能是一个String.有没有办法在函数签名中进一步约束它,以便它只能是一个字符串"right","left"或"center"?
在朱莉娅,座右铭应该是"有一种类型!".处理这种情况的一种方法是创建一个带有构造函数的类型,该构造函数只允许您想要的值(并且可能以更有效的方式存储它们).这是一个例子:
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")
Run Code Online (Sandbox Code Playgroud)
注意:我的例子是用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))
Run Code Online (Sandbox Code Playgroud)
这将允许您执行以下操作:x = MyDirection("left"),它将创建MyDirection类型的不可变对象{:left}.