I don't really get what that version is doing – it seems to throw out the d
argument. Here's how I would write it:
type Foo{T}
t::T
Foo(d::T=zero(T)) = new(d)
end
Foo{T}(d::T) = Foo{T}(d)
There's not duplication of logic this way.
On Tue, Feb 10, 2015 at 1:24 PM, Michael Francis <[email protected]>
wrote:
> Annoyingly this inverts the behavior, so I have to provide both inner and
> outer constructors for this and the obvious outer constructor may not be
> defined as it calls itself. (There is a solution below. )
>
> Additionally it seems confusing that the new() method in in the
> constructor does not call the zero parameter constructor, e.g. there is not
> constructor chaining
>
> If you run this example you get an undefined value of t in Foo and the
> un-typed version does not work
>
> abstract Bar
> type Foo{T} <: Bar
> t::T
> Foo() = new( zero( T ) )
> Foo( d::T) = ( this = new() ; this )
> end
>
>
>
> Foo{Int}( 1)
> Foo( 1)
>
>
> The below works but is not obvious - without the Foo{T} loops into
> eternity. Note the duplication of code between the one arg constructor and
> the two arg.
>
> abstract Bar
> type Foo{T} <: Bar
> t::T
> Foo() = new( zero( T ) )
> Foo( d::T) = ( this = new( zero( T ) ; this )
> end
> *Foo{T}(d::T) = Foo{T}( d )*
>
>
> On Tuesday, February 10, 2015 at 12:47:19 PM UTC-5, Stefan Karpinski wrote:
>>
>> Supplying the type parameter explicitly invokes the inner constructor.
>> For non-parametric types, there's a single generic function that both inner
>> and outer constructor methods belong to – so the only distinction between
>> the inner and outer ones is where they occur (and thus whether they have
>> access to new or not). For parametric types, however, inner constructor
>> methods are added to the Foo{T} object whereas outer constructor methods
>> are added to the Foo object. It's a but confusing, I know.
>>
>> On Tue, Feb 10, 2015 at 12:38 PM, Michael Francis <[email protected]>
>> wrote:
>>
>>> But why is the outer constructor not called in this case ?
>>>
>>> On Tuesday, February 10, 2015 at 12:35:44 PM UTC-5, Stefan Karpinski
>>> wrote:
>>>>
>>>> The inner constructor only has a zero-argument method:
>>>>
>>>> julia> Foo{Int}()
>>>> Foo{Int64}(0)
>>>>
>>>>
>>>> If you add a second inner constructor method, then you can call it.
>>>>
>>>> On Tue, Feb 10, 2015 at 12:15 PM, Michael Francis <[email protected]>
>>>> wrote:
>>>>
>>>>> A slightly simplified example, If I pin the type parameter I am unable
>>>>> to create the new object. I'm sure I'm missing something obvious here but
>>>>> given that Int 1 defaults to Int64 on my system I would expect both lines
>>>>> to work ?
>>>>>
>>>>> abstract Bar
>>>>> type Foo{T} <: Bar
>>>>> t::T
>>>>> Foo() = new( zero( T ) )
>>>>> end
>>>>> Foo{T}( d::T) = ( this = Foo{T}() ; this.t = d; this )
>>>>>
>>>>> Foo{Int}( 1) # Foo{Int64} has no method matching Foo{Int64}(::Int64)
>>>>> Foo( 1) # Works
>>>>>
>>>>
>>>>
>>