朱莉娅:多种类型具有相同的功能吗?

时间:2018-08-27 19:11:11

标签: function methods julia dispatch

我有一个在矢量上定义的大函数,但我希望它也可以使用单个值。我希望第一个参数的类型可以是向量或数字。

我将以下内容归结为:

<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
<title>Documento PHP</title>
<style>
    h1{
        text-align:center;
    }

    table{
        background-color:#FFC;
        padding:5px;
        border:#666 5px solid;
    }

该函数对矢量有效,但对数字无效。

function bigfunction(x::Vector, y::Float64=0.5)

  # lots of stuff
  z = x .+ y
  return z
end


bigfunction(x::Number) = bigfunction()

我应该像有时候看到的那样对bigfunction([0, 1, 3]) bigfunction(2) 做些什么?还是以其他方式重新定义方法?

2 个答案:

答案 0 :(得分:1)

还是鸭型。请记住,功能始终会自动进行专业化,因此选择受约束的调度根本不会影响性能。

function bigfunction(x, y=0.5)

  # lots of stuff
  z = x .+ y
  return z
end

这将与性能一样,但可以在更多类型上使用。参见this blog post on type-dispatch designs for more information

答案 1 :(得分:1)

这个问题和答案帮助我说明了Chris Rackauckas在伟大的blog post中对Julia的类型调度提出的观点。

我已将响应整理为以下代码:

# I ran this only in Julia 1.0.0.

## ========== Original function ==========
## function bigfunction(x::Vector, y::Float64=0.5)
##     # lots of stuff
##     z = x .+ y
##     return z
## end
## bigfunction(x::Number) = bigfunction()
## println(bigfunction([0, 1, 3]))
## println(bigfunction(2))
## ---------- Output has ERROR ----------
## [0.5, 1.5, 3.5]
## ERROR: LoadError: MethodError: no method matching bigfunction()


# ========== Answer Suggested by Picaud Vincent in comments ==========
# Note use of Union in function signature.
function bigfunction(x::Union{Vector, Number}, y::Float64=0.5)
    # lots of stuff
    z = x .+ y
    return z
end
println(bigfunction([0, 1, 3]))
println(bigfunction(2))
## ---------- Output Okay ----------
## [0.5, 1.5, 3.5]
## 2.5


# ========== Answer Suggested by Robert Hönig in comments ==========
# Note change in line right after function definition.
function bigfunction(x::Vector, y::Float64=0.5)
    # lots of stuff
    z = x .+ y
    return z
end
bigfunction(x::Number) = bigfunction([x])
println(bigfunction([0, 1, 3]))
println(bigfunction(2))
## ---------- Output Okay ----------
## [0.5, 1.5, 3.5]
## 2.5


# ========== Answer Suggested by Chris Rackauckas ==========
# Note change in function signature using duct typing--no type for x.
function bigfunction(x, y=0.5)
    # lots of stuff
    z = x .+ y
    return z
end
println(bigfunction([0, 1, 3]))
println(bigfunction(2))
## ---------- Output Okay ----------
## [0.5, 1.5, 3.5]
## 2.5