gpt4 book ai didi

methods - Julia:为自定义类型定义方法

转载 作者:行者123 更新时间:2023-12-03 21:08:53 24 4
gpt4 key购买 nike

如果之前有人回答过这个问题,我深表歉意,我在搜索结果中没有找到直接的答案。
我正在学习“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)

关于methods - Julia:为自定义类型定义方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65293891/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com