Trouble deducing type parameter with inner constructor

92 views
Skip to first unread message

Magnus Lie Hetland

unread,
Aug 25, 2014, 2:04:55 PM8/25/14
to julia...@googlegroups.com
What is the right approach if I want (1) to use an inner constructor, which does some modification/normalization to the arguments, and (2) I want proper type parameter deduction from the arguments? Do I need to write a separate function or something?

I'm not even sure what's going on here (i.e., why it doesn't work with the inner constructor) – or how I could make it work with the outer constructor…

immutable A{N}

    x::NTuple{N, Int}

    y::Int

    A(x, y) = new(x, y + 1)

end


#a = A((1, 2), 3)       # Doesn't work

a = A{2}((1, 2), 3)     # Works (w/cumbersome param)

println(a)


abstract C


immutable B{N} 

    x::NTuple{N, Int}

    y::Int

end


#B(x, y) = B(x, y + 1)  # Stack overflow...

b = B((1, 2), 3)        # Works (w/wrong answer)

println(b)


What am I doing wrong?

Magnus Lie Hetland

unread,
Aug 26, 2014, 3:14:10 AM8/26/14
to julia...@googlegroups.com
OK, this works:

immutable A{N}

    x::NTuple{N, Int}

    y::Int

    A(x, y) = new(x, y + 1)

end


A{N}(x::NTuple{N, Int}, y::Int) = A{N}(x, y)


But why is this necessary? (Adding type decl. to the internal constructor doesn't seem to do anything useful.) And why is it not necessary if I don't have an internal constructor?

(Oh, by the way: Please ignore the abstract C in the previous example ;-))

Tobias Knopp

unread,
Aug 26, 2014, 4:24:38 AM8/26/14
to julia...@googlegroups.com
I don't really know if this is a bug or if there is some good technical reason for this.
What seems to happen is that the definition

A(x, y) = new(x, y + 1)

removes the default constructor. You can see this by typing "A" on the REPL (or methods(A))

Magnus Lie Hetland

unread,
Aug 26, 2014, 4:41:30 AM8/26/14
to julia...@googlegroups.com
Hm, yes. Is this somehow related to the default constructor stuff added in 0.3 (linked to issues #4026 and #7071)? Not that I see exactly how they'd be related, except that they're linked to the same topic :-} Could it be because the default argument uses Any for its argument types, and me adding a constructor with exactly that signature prohibits it from being constructed (reasonable enough)? But even so, not figuring out the type parameter seems like it might be a bug…? (Or maybe it's just a feasible specific case of an infeasible general problem that I haven't noticed?)

Tobias Knopp

unread,
Aug 26, 2014, 5:39:33 AM8/26/14
to julia...@googlegroups.com
Magnus,

Please feel free to file a new issue. Even if it is intentional it might have to be better documented.

Cheers,

Tobi

Magnus Lie Hetland

unread,
Aug 26, 2014, 6:01:00 AM8/26/14
to julia...@googlegroups.com
Reply all
Reply to author
Forward
0 new messages