Multiple dispatch是julia语言的一大特色,也叫多重分派。可以使Julia更通用更快捷。
为了理解Multiple dispatch,我们看下面的例子。
f(x) = x^2
julia语言会自动判断接收参数的类型并对其进行运算
f(10) = 100
而对于f([1,2,3,4])则会报错,因为在数学里没有定义两个向量相乘,只定义了两个向量的内积
**指定输入参数的类型**
然而,julia允许我们可以显示地指定哪些类型参数可以作为输入参数
例如:func(x::String,y::String) = println( "My inputs $x and $y are strings!" )
func( "a", "b" )的结果为 My inputs a and b are strings!
而func( 1., 2. )会有如下错误:MethodError: no method matching foo(::Int64, ::Int64)
没有匹配的method
我们接下来使函数可以对整形Int数据进行运算
func( x::Int, y::Int ) = println( "My inputs $x and $y are strings!" )
func( 3, 4 ) = My inputs 3 and 4 are strings!
在这里要注意:声明func( x::Int, y::Int ) = println( "My inputs $x and $y are strings!" )后,并没有替换前面声明的func(x::String,y::String) = println( "My inputs $x and $y are strings!" ),而是作为对之前func的补充
所以现在func()里的变量只要是字符串和整型数据的类型,都是“合法的”。
如果要查看某个函数有几种method,使用method函数既可以查看
method(func)的返回值为
func(x::Int64, y::Int64)
func(x::String, y::String)
类似地,也可以查看运算符“+”:method(+)'
要查看在调用泛型函数时正在调用哪个method,可以使用@which宏
@which func(3,4)返回值为:func(x::Int64, y::Int64)
@which 3.3 + 4.4返回值为:+(x::Float64, y::Float64)
我们还可以继续对func添加method
func(x::Number, y::Number) = println( "My $x and $y are both numbers!" ) # Number类型包括Int,Float64
我们还可以添加Bool类型
func(x::Bool, y::Bool) = println( "My $x and $y are both Bool!" )
**如果对函数func没有进行显式参数类型说明,他可以进行自我参数识别**
Julia:Multiple dispatch
最新推荐文章于 2024-06-11 23:38:04 发布