Julia: @generated=>多姿多彩!

Julia生成函数解析
本文介绍了Julia语言中一种特殊宏@generated,该宏允许定义所谓的生成函数。这些函数可以根据参数类型生成特定代码,比多重分发提供更大的灵活性。文章通过示例展示了如何使用@generated宏来根据不同类型的输入返回不同形式的输出。

Julia doc 关于 @generated:
A very special macro is @generated, which allows you to define so-called generated functions. These have the capability to generate specialized code depending on the types of their arguments with more flexibility and/or less code than what can be achieved with multiple dispatch. While macros work with expressions at parsing-time and cannot access the types of their inputs, a generated function gets expanded at a time when the types of the arguments are known, but the function is not yet compiled.

方便吧!

@generated function bar(x) # 没有@generated会报错
          if x <: Integer
              return :(x^2)   # 注意,:表示quoted expression,不能少!
          elseif x<:AbstractString
              return :(string(x,", hello world!")) # 注意,不能少“:”
          else 
              return :(x*3) # 注意,不能少“:”
          end
      end

有趣吧!

       dat1 =bar(5.0) # 15.0
       dat2 =bar(5)   # 25
       dat3 =bar("wo")# wo,hello world
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值