julia - 将参数限制为 Julia 函数签名中的一组值

标签 julia

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/

相关文章:

shell - Julia 中的多行命令

web-scraping - Julia :网站抓取?

types - 在 Julia 中,您可以指定可调用函数参数的参数和返回值吗?

statistics - Julia - describe() 函数显示不完整的汇总统计信息

export - 保存决策树模型以供以后在 Julia 中应用

csv - 导入 csv 在 Jupyter 笔记本中的初始位置 Julia 中返回编码标识符

julia - 如何使规范化适用于 Julia 中的所有类型的数组?

multiprocessing - 使用 DistributedArrays 时出现 BoundsError

output - 在 Julia 中不缓冲地写入输出

dataframe - 从 Julia DataFrame 创建加权图