【问题标题】:Julia: define method for custom typeJulia:为自定义类型定义方法
【发布时间】:2021-03-25 09:07:32
【问题描述】:

如果之前已经回答过这个问题,我深表歉意,我在搜索结果中没有找到直接的答案。

我正在阅读“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

另一个快速的问题,我还没有进入函数章节,但它引起了我的注意,函数末尾没有“返回”,我猜如果没有说明函数将返回最后的评估值,对吗?

【问题讨论】:

    标签: methods julia custom-type


    【解决方案1】:

    这似乎使用了非常古老的 Julia 语法(我认为是从 0.6 版开始)。我想你只是想要function +(a::LSD, b::LSD)

    【讨论】:

    • 谢谢奥斯卡,你是对的。对不起,我还不能投票。我想这是采用像 Julia 这样的年轻语言的注意事项之一。尽管如此,我仍然对此充满热情!
    • 欢迎来到社区! Julia 1.0 于 2018 年 8 月发布,所以我建议尝试使用更新的东西。 1.0 或更高版本的任何内容都应该在当前版本中运行良好。
    • 我认为这是不正确的,即使是 0.6 之前的版本。它使用 LSD 作为类型 parameter 而不是类型,所以这永远不会正确。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-25
    • 1970-01-01
    • 2021-08-02
    • 2022-11-03
    • 1970-01-01
    相关资源
    最近更新 更多