when you do
immutable Dice end
or
type Dice end
you create a singleton type -- there can be only one instance (or all
instances are that identical single instance).
To realize a singleton type, call it:
myDice = Dice(); myCoin = Coin()
now, you can use
choose(x::Dice) = println("throw the dice")
choose(myDice)
throw the dice
On Thursday, March 10, 2016 at 12:02:09 PM UTC-5, ben wrote:
>
> Hi everyone,
>
> One of the many cool things we can do in Julia is use multiple dispatch to
> avoid a "method" argument followed by a "if" construct sending to back-end
> functions. I sometimes get confused about which of the following two ways
> of achieving this is better:
>
> ~~~
> immutable Dice end
> immutable Coin end
>
> takedecision{H <: Dice}(::Type{H})=println("throw a dice")
> takedecision{H <: Coin}(::Type{H})=println("flip a coin")
> makedecision(::Dice)=println("throw a dice")
> makedecision(::Coin)=println("flip a coin")
>
> takedecision(Dice)
> takedecision(Coin)
> makedecision(Dice())
> makedecision(Coin())
> ~~~
>
> If the method has "tuning parameters" (like the type of Dice or of Coin),
> the second way is much better, using inner fields `method.tuningparameter`
> and constructor `Method(tuningparameter)`. But if the method type is a pure
> "label" type without any additional content, both ways work. The first one
> is uglier in the source code but nicer for the user and may be more
> faithful to the concept (I want to make a decision by throwing a coin, not
> by throwing this particular coin). Indeed see the confusion caused by
> Gridded(Linear()) in this other topic:
> https://groups.google.com/forum/#!topic/julia-users/0cV6v-FJD7c
>
> Am I missing something key in terms of the pros and cons of each of these
> two ways? Is there a principled good practice?
>
> Best
>
> Ben
>
>