gpt4 book ai didi

julia - 是否可以在 NOT-a-type 上进行多次调度?

转载 作者:行者123 更新时间:2023-12-04 09:24:36 27 4
gpt4 key购买 nike

为了简化,我正在尝试编写一个带有两个参数的函数,其中:

  • 基本方法接受两个整数作为参数

    func(x::Int, y::Int) = 某事
  • 其他方法接受一个或两个参数作为任意类型,将这些参数映射到整数,并调用基本方法
  • 其他方法接受一个或两个参数作为数组(或::Colon 类型),并通过应用适当的先前方法 (1) 或 (2) 逐元素生成数组。

  • 不出所料(事后看来),这种方法会产生方法歧义。鉴于提供给函数的参数类型,Julia 会选择具有最具体类型的有效方法。但是如果 x 是一个数组并且 y 是一个 Int,那么以下方法同样是特定的,而 Julia 不知道该调用哪一个:
  • func(x::Any, y::Int)
  • func(x::Array, y::Any)

  • 我想做类似的事情
  • func(x::T, y::Int) T <: any_so_long_as_not_array = func(map_x_to_Int(x), y)
  • func(x::Array, y::Any) = (el -> func(el, y)).(x)

  • 有没有非类型类型之类的东西?我在想这个错误的方式吗?有没有解决这类问题的规范方法?

    对于上下文,我正在尝试为我编写的结构实现 Base.getindex,并且当结构的内容可能有所不同时,我希望 getindex 支持多种不同的方式来索引结构。在幕后,结构中的元素由整数索引,但用户可能使用几乎任意的非整数类型来索引结构中的元素(我不想强制用户使用特定类型来索引元素)。

    最佳答案

    您可以指定 (Array, Int) 案例,然后添加不太具体的方法:

    julia> func(x::Array, i::Int) = 0
    func (generic function with 1 method)

    julia> func(x, i::Int) = 1
    func (generic function with 2 methods)

    julia> func(x::Array, i) = 2
    func (generic function with 3 methods)

    julia> methods(func)
    # 3 methods for generic function "func":
    [1] func(x::Array, i::Int64) in Main at REPL[1]:1
    [2] func(x, i::Int64) in Main at REPL[2]:1
    [3] func(x::Array, i) in Main at REPL[3]:1

    关于julia - 是否可以在 NOT-a-type 上进行多次调度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60196592/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com