(Nice on the type assert, but worth pointing out that the 2-argument outer 
constructor is not type-inferrable.)

--Tim

On Thursday, March 31, 2016 01:10:15 PM Mauro wrote:
> I think this is fine and idiomatic
> 
> julia> type A{B}
>            x::Float64
>            function A(x)
>                B::Bool # asserts that B is indeed a Bool
>                new(x)
>            end
>        end
> 
> julia> A(x, b::Bool) = A{b}(x)
> A{B}
> 
> julia> A(5, true)
> A{true}(5.0)
> 
> julia> function dothing(a::A{true})
>           println("do thing with true")
>        end
> dothing (generic function with 1 method)
> 
> julia> function dothing(a::A{false})
>           println("do thing with false")
>        end
> dothing (generic function with 2 methods)
> 
> julia> dothing(A(5,true))
> do thing with true
> 
> julia> dothing(A(5,false))
> do thing with false
> 
> On Thu, 2016-03-31 at 04:51, Chris <[email protected]> wrote:
> > Here's my current dilemma, (hopefully) explained by this simple example:
> > 
> > I have a composite type that has a bool field:
> > 
> > type A
> > 
> >   x::Float64
> >   b::Bool
> > 
> > end
> > 
> > I have a function with different behavior based on the value of A.b. The
> > manual
> > <http://docs.julialang.org/en/release-0.4/manual/types/#value-types>
> > suggests the following solution:
> > 
> > function dothing(a::A, ::Type{Val{false}})
> > 
> >    ...
> > 
> > end
> > 
> > function dothing(a::A, ::Type{Val{true}})
> > 
> >   ...
> > 
> > end
> > 
> > That's fine, but now I have to call the function as dothing(a, Val{a.b}),
> > which just strikes me as slightly redundant/verbose. Is there some way to
> > make this more compact, i.e. just dothing(a), while still avoiding the
> > check of a.b inside the function? Perhaps parameterizing the type A
> > itself?
> > 
> > Hopefully I made myself relatively clear. Thanks in advance.

Reply via email to