El miércoles, 13 de mayo de 2015, 10:58:18 (UTC-5), Elburz Sorkhabi
escribió:
>
> At that point would it make more sense to have a constructor function that
> would be called if a speed bool is passed at all and one for when no bool
> passed?
> In my use case the bool would only be passed if it needed to be true and
> would be fine defaulting as false.
>
> Would that be more straight forward than type values?
>
>
I think that both in Python and Julia an approach using type hierarchies
(inheritance) is nice. In Julia this could be as follows.
There are two options for the joint setup part -- using invoke, which I
find a bit clumsy, and just making a generic setup routine that you call
for each object after the object-specific part.
abstract Car
setup(c::Car) = "do some setup for a generic car"
type FastCar <: Car
end
type SlowCar <: Car
end
setup(f::FastCar) = (println("Setting up a fast car"); invoke(setup,
(Car,), f))
setup(s::SlowCar) = (println("Setting up a slow car"); invoke(setup,
(Car,), s))
generic_setup(c::Car) = println("Alternatively, do generic setup
separately")
move(c::Car) = println("Moving the car $c")
f = FastCar()
s = SlowCar()
setup(f); generic_setup(f)
setup(s); generic_setup(s)
move(f)
move(s)
David
> --
> es
>
> _____________________________
> From: Tamas Papp <[email protected] <javascript:>>
> Sent: Wednesday, May 13, 2015 11:23 AM
> Subject: Re: [julia-users] How to use Multiple Dispatch for Type
> Constructors
> To: <[email protected] <javascript:>>
>
>
> Julia cannot dispatch on values, but it can dispatch on types
> parametrized by values. The canonical way of doing this is value types
> (see in the Types section of the manual), but pretty much any other
> parametrized type would work:
>
> carsetup(::Type{Val{:fast}}) = "fast"
> carsetup(::Type{Val{:slow}}) = "slow"
>
> carsetup(Val{:fast}) # => "fast"
>
> HTH,
>
> Tamas
>
> On Wed, May 13 2015, Elburz Sorkhabi <[email protected] <javascript:>>
> wrote:
>
> > I was wondering if I could make a constructor function that works with
> > multiple dispatch. My goal is to have a bool that can be set to true or
> > false on creation as an argument, which would then change the way the
> > constructor works. I could do it with an if statement, but I was curious
> > about the more Julian way to approach it. I believe I'm looking for outer
> > constructors, but I couldn't seem to find a good example, and the wiki
> is a
> > little terse :) Below is my Python brain at work, but I feel like outer
> > constructors using multiple dispatch should be how I approach it. Thanks!
> >
> > type Car
> > fast::Bool
> >
> > function Car(fast::Bool)
> > if fast == true
> > do fast car specific setup
> > else
> > do slow car specific setup
> > end
> >
> > do general car setup that both cars need
> > end
> > end
>
>
>