Luis
Luis

Reputation: 65

Julia: define method for custom type

I apologize if this has been answered before, I didn't find a straight answer for this among my search results.

I'm going through "Learn Julia The Hardway" and I can't really find where's the difference in my code vs the example in the book. Whenever I run it I get the following error:

TypeError: in Type{...} expression, expected UnionAll, got a value of type typeof(+)

Here's the code:

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

Another quick question, I haven't got yet to the functions chapter, but it catches my attention that there is no "return" at the end of the functions, I'm guessing that if it isn't stated a function will return the last evaluated value, am I right?

Upvotes: 4

Views: 428

Answers (1)

Oscar Smith
Oscar Smith

Reputation: 6398

This appears to be using very old Julia syntax (I think from version 0.6). I think you just want function +(a::LSD, b::LSD)

Upvotes: 6

Related Questions