Julia:Multiple dispatch

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没有进行显式参数类型说明,他可以进行自我参数识别**
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值