Conversion of parameters in function call

question

#1

Hello,

I’d like to automatically convert some parameters of a function.

I defined a type using

type Pin
    number::Int
end

and a function

function hi(pin::Pin)
    println(pin)
end

I can do this

pin = Pin(10)
hi(pin)

but I’d like to also be able to do

hi(10)

I tried to define a conversion using

convert(::Type{Pin}, pin::Int) = Pin(pin)

I can test it using:

println(convert(Pin, 10))

it displays Pin(10)

but

hi(10)

raises MethodError

Is there a better way to do this instead of doing

function hi(pin::Int)
    hi(Pin(pin))
end

because this kind of solution is no very viable if I want to have an “automatic” conversion of several parameters in a function call.

Kind regards


#2

No. Doing that is incompatible with multiple dispatch.


#3

It’s not clear what you want to do with the several parameters, but maybe something like this:

function hi(pin)
    hi(Pin(pin))
end

function hi(params...)
    return map(Pin, params)
end

julia> hi(3, 4)
(Pin(3),Pin(4))

#4

Would such approach meet your requirements?

type Pin
    number::Int
end

convert(::Type{Pin}, pin::Int) = Pin(pin)
convert(::Type{Pin}, pin::Pin) = pin # or Pin(pin.number)

function hi(pin::Pin)
    println(pin)
end

function hi(params...)
    for p in params
        hi(convert(Pin, p))
    end
end

In this way you can write hi(10, Pin(20), 30, Pin(40)) - you can pass to hi anything that is convertible to Pin.


#5

If you don’t need to type the arguments, you could also do:

function hi(arg)
    pin = convert(Pin, arg)
    println(pin)
end

And do appropriate error handling in convert!


#6

Although you didn’t ask, I’ll point out that for a composite type with a single Int as its member, you would most likely prefer immutable (called struct in 0.6 and higher) rather than type (called mutable struct in 0.6 and higher). Declaring Pin as immutable will in many circumstances improve performance, prevent subtle bugs and improve readability.


#7

Thanks all for your nice help.