Parameteric Function of Types

52 views
Skip to first unread message

Derek Gaston

unread,
Oct 28, 2016, 1:55:47 PM10/28/16
to julia-users
I can't quite seem to get the right syntax for creating methods that are keyed off of subtypes (as a parameter).

Say I have:

abstract foo
abstract bar <: foo

I want to create a function that is like so:

function doStuff(::Type{foo})
end

in such a way that I can call it with "Type{bar}".  i.e.:  doStuff(Type{bar})

I understand that:

# Returns true:
issubtype(bar, foo)

# Returns false:
issubtype(Type{bar}, Type{foo})

And I understand why.

So... I tried to define:

function doStuff{T}(::Type{T<:foo})
end

But it tells me that: "WARNING: static parameter T does not occur in signature" (it looks like it does to me! :-)... so that's not the right answer.

Obviously I'm just thinking about the problem incorrectly... so can someone shed some light on what's up here?

Before you ask: I really do need to operate on the _types_ and not on instances of the objects themselves (which would obviously be straightforward to do).




Also: a (related) follow-on question.  What is the correct/preferred way to do the following:

function createSomething{T}()
  return T()
end

(obviously, this is a toy example, my real application of this is not trivial)

Is it to do:

function createSomething{T}(::Type{T})
  return T()
end

?




Thanks for any help!

Derek

Isaiah Norton

unread,
Oct 28, 2016, 2:38:45 PM10/28/16
to julia...@googlegroups.com
On Fri, Oct 28, 2016 at 12:07 PM, Derek Gaston <frie...@gmail.com> wrote:
I can't quite seem to get the right syntax for creating methods that are keyed off of subtypes (as a parameter).

Say I have:

abstract foo
abstract bar <: foo

I want to create a function that is like so:

function doStuff(::Type{foo})
end

in such a way that I can call it with "Type{bar}".  i.e.:  doStuff(Type{bar})

I understand that:

# Returns true:
issubtype(bar, foo)

# Returns false:
issubtype(Type{bar}, Type{foo})

And I understand why.

So... I tried to define:

function doStuff{T}(::Type{T<:foo})
end

But it tells me that: "WARNING: static parameter T does not occur in signature" (it looks like it does to me! :-)... so that's not the right answer.

function doStuff{T <: foo}(::Type{T})
end
 

Obviously I'm just thinking about the problem incorrectly... so can someone shed some light on what's up here?

Before you ask: I really do need to operate on the _types_ and not on instances of the objects themselves (which would obviously be straightforward to do).




Also: a (related) follow-on question.  What is the correct/preferred way to do the following:

function createSomething{T}()
  return T()
end


If you want to implement the "factory pattern", that can be simulated, but I'm not sure it's necessary (or useful) in Julia.

See also:


Reply all
Reply to author
Forward
0 new messages