Julia:为自定义类型定义方法
如果之前有人回答过这个问题,我深表歉意,我在搜索结果中没有找到直接的答案。
我正在学习“Learn Julia The Hardway”,但我真的找不到我的代码与书中示例的区别在哪里。每当我运行它时,我都会收到以下错误:
TypeError: in Type{...} expression, expected UnionAll, got a value of type typeof(+)
这是代码:
struct LSD
pounds::Int
shillings::Int
pence::Int
function LSD(l,s,d)
if l<0 || s<0 || d<0
error("No negative numbers please, we're british")
end
if d>12 error("That's too many pence") end
if s>20 error("That's too many shillings") end
new(l,s,d)
end
end
import Base.+
function +{LSD}(a::LSD, b::LSD)
pence_s = a.pence + b.pence
shillings_s = a.shillings + b.shillings
pounds_s = a.pounds + b.pounds
pences_subtotal = pence_s + shillings_s*12 + pounds_s*240
(pounds, balance) = divrem(pences_subtotal,240)
(shillings, pence) = divrem(balance,12)
LSD(pounds, shillings, pence)
end
另一个快速问题,我还没有进入函数章节,但它引起了我的注意,函数末尾没有“返回”,我猜如果没有说明,函数将返回最后评估值,我说的对吗?
回答
这似乎使用了非常古老的 Julia 语法(我认为从 0.6 版开始)。我想你只是想要function +(a::LSD, b::LSD)
- I don't think that would be correct, even pre-0.6. It's using `LSD` as a type *parameter* instead of as a type, so this would never have been correct.