Starting 0.6 it is possible to create parametric methods in Julia using where syntax. According to the release notes of 0.6 version, where syntax
can be used anywhere a type is accepted
Now consider the following contrived example:
function (rng::R)() where {R <: Range}
return first(rng)
end
which, when I attempt to compile it, gives the following error:
ERROR: function type in method definition is not a type
So my question is what is the proper way to create parametric functors in Julia 0.6+?
Ohkay, I get what you are trying to do basically. To understand functors here is a short example code.
julia> struct Student
name::String
end
julia> function (::Student)()
println("Callable of Student Type!")
end
julia> object = Student("JuliaLang")
Student("JuliaLang")
julia> object()
Callable of Student Type!
but when I try to create the parametric functors, it throws out the error similar to yours!
julia> function (::T)() where {T <: Student}
println("Callable of Student Type!")
end
ERROR: function type in method definition is not a type
This problem is actually still OPEN as a issue as #gnimuc rightly pointed out.
You mix up two things
parametric methods e.q. julia> same_type(x::T, y::T) where {T} = true
function-like objects e.g. julia> function (p::Polynomial)(x) ... end
To my knowledge there is no "parametric function-like objects"
However, the following code should be the same of what you intend.
Julia> function (rng::Range)()
return first(rng)
end
cannot add methods to an abstract type
The current docu does not mention any limitation of function-like objects to concrete type, but unfortunately Julia doesn't accept it anyway.
Related
Julia permits function and method definitions with unnamed arguments.
This is not mentioned in the functions documentation, nor is it explicitly discussed in the methods documentation. For example:
function myfunc(::Int)
println("Hello!")
end
How should I describe this behavior (I've googled "anonymous arguments" without success), and when is it useful?
This behavior is useful for method dispatch, when you care only about argument type not argument value. Most often this is a case when what you dispatch on is a singleton type.
An example is:
julia> Vector{String}(undef, 3)
3-element Array{String,1}:
#undef
#undef
#undef
This function is defined in the following way:
Array{T,1}(::UndefInitializer, m::Int) where {T} =
ccall(:jl_alloc_array_1d, Array{T,1}, (Any, Int), Array{T,1}, m)
And you can see that we only care that the first argument was of UndefInitializer type, which is in turn defined as:
struct UndefInitializer end
const undef = UndefInitializer()
We see that UndefInitializer is a singleton type, so we do not care about the value of a variable of this type, but only about its type.
Another common singleton type in Base is Missing. Here are example definitions from Base of standard functions getting a Missing as an argument:
for f in (:(acos), :(acosh), :(asin), :(asinh), :(atan), :(atanh),
:(sin), :(sinh), :(cos), :(cosh), :(tan), :(tanh),
:(exp), :(exp2), :(expm1), :(log), :(log10), :(log1p),
:(log2), :(exponent), :(sqrt))
#eval $(f)(::Missing) = missing
end
(again - you can see that we do not care about the value of the variable - we know its type is Missing so we return missing)
In the Julia manual you have examples of such methods e.g. here but admittedly as far as I can tell the manual does not give a name for this style of method definition.
I am learning Julia and for that purpose I am building a simulation of a scheduler for some non specified task. For this I want to create an abstract type, which represents the idea of state. A task could be in any state Accepted, Unfulfilled, Running, Finished:
abstract RequestState
Then I add some concrete states, which have RequestState as superstate:
immutable StateAccepted <: RequestState
name :: String
end
And because each state is immutable anyway and it doesn't have an interesting structure, all instances are the same, so I instantiate an instance of the above type to use:
const Accepted = StateAccepted("Accepted")
I generate this with a macro, perhaps it is relevant.
Now comes the problem. I want to write a function, which checks valid transitions. I only have a skeleton at this point:
function checkTransition{T <: RequestState, Q <: RequestState}(t :: T, q :: Q) :: Bool
return true
end
I assumed I should read the expression:
T <: RequestState
As something like forall T which is a subtype of RequestState, but I think this is wrong.
I would expect that this code compiles. The problem is that I don't understand the error and also can't find anything in the documentation. Note that this could be, because I am unfamiliar with the language. The relevant error is:
Error During Test
Expression evaluated to non-Boolean
Expression: checkTransition(Accepted,Running)
Value: ResourceScheduler.StateRunning("Running")
ERROR: LoadError: There was an error during testing
in record(::Base.Test.FallbackTestSet, ::Base.Test.Error) at ./test.jl:397
in do_test(::Base.Test.Returned, ::Expr) at ./test.jl:281
in include_from_node1(::String) at ./loading.jl:488
in process_options(::Base.JLOptions) at ./client.jl:262
in _start() at ./client.jl:318
while loading /home/eklerks/.julia/v0.5/ResourceScheduler/test/runtests.jl
How would I make a generic function accepting only arguments of subtypes of RequestState?
EDIT:
As requested the offending test:
#test checkTransition(Accepted, Running)
But this didn't work out, because I forgot to update and install my package after I changed it. Before that change it read:
function checkTransition{T <: RequestState, Q <: RequestState}(t :: T, q :: Q) :: Q
return q
end
Which was the source of the error. Type Q is indeed not a Boolean. I was experimenting with the type system at that moment.
While your code should work, typically one writes
checkTransition(t::RequestState, q::RequestState) = true
instead of using the unnecessary T <: RequestState parameterization. Note that f{T <: X}(::T) should not be read as "for all T subtype of X", but rather "there exists T subtype of X", as this is an existential type and not a universal type.
The error you're getting is due to checkTransition(Accepted,Running) returning a non-boolean, which must be due to a mistake unrelated to the code that you've posted.
The problem is the following:
I have an abstract type MyAbstract and derived composite types MyType1 and MyType2:
abstract type MyAbstract end
struct MyType1 <: MyAbstract
somestuff
end
struct MyType2 <: MyAbstract
someotherstuff
end
I want to specify some general behaviour for objects of type MyAbstract, so I have a function
function dosth(x::MyAbstract)
println(1) # instead of something useful
end
This general behaviour suffices for MyType1 but when dosth is called with an argument of type MyType2, I want some additional things to happen that are specific for MyType2 and, of course, I want to reuse the existing code, so I tried the following, but it did not work:
function dosth(x::MyType2)
dosth(x::MyAbstract)
println(2)
end
x = MyType2("")
dosth(x) # StackOverflowError
This means Julia did not recognize my attempt to treat x like its "supertype" for some time.
Is it possible to call an overloaded function from the overwriting function in Julia? How can I elegantly solve this problem?
You can use the invoke function
function dosth(x::MyType2)
invoke(dosth, Tuple{MyAbstract}, x)
println(2)
end
With the same setup, this gives the follow output instead of a stack overflow:
julia> dosth(x)
1
2
There's a currently internal and experimental macro version of invoke which can be called like this:
function dosth(x::MyType2)
Base.#invoke dosth(x::MyAbstract)
println(2)
end
This makes the calling syntax quite close to what you wrote.
In Julia, is there any way to get the name of a passed to a function?
x = 10
function myfunc(a)
# do something here
end
assert(myfunc(x) == "x")
Do I need to use macros or is there a native method that provides introspection?
You can grab the variable name with a macro:
julia> macro mymacro(arg)
string(arg)
end
julia> #mymacro(x)
"x"
julia> #assert(#mymacro(x) == "x")
but as others have said, I'm not sure why you'd need that.
Macros operate on the AST (code tree) during compile time, and the x is passed into the macro as the Symbol :x. You can turn a Symbol into a string and vice versa. Macros replace code with code, so the #mymacro(x) is simply pulled out and replaced with string(:x).
Ok, contradicting myself: technically this is possible in a very hacky way, under one (fairly limiting) condition: the function name must have only one method signature. The idea is very similar the answers to such questions for Python. Before the demo, I must emphasize that these are internal compiler details and are subject to change. Briefly:
julia> function foo(x)
bt = backtrace()
fobj = eval(current_module(), symbol(Profile.lookup(bt[3]).func))
Base.arg_decl_parts(fobj.env.defs)[2][1][1]
end
foo (generic function with 1 method)
julia> foo(1)
"x"
Let me re-emphasize that this is a bad idea, and should not be used for anything! (well, except for backtrace display). This is basically "stupid compiler tricks", but I'm showing it because it can be kind of educational to play with these objects, and the explanation does lead to a more useful answer to the clarifying comment by #ejang.
Explanation:
bt = backtrace() generates a ... backtrace ... from the current position. bt is an array of pointers, where each pointer is the address of a frame in the current call stack.
Profile.lookup(bt[3]) returns a LineInfo object with the function name (and several other details about each frame). Note that bt[1] and bt[2] are in the backtrace-generation function itself, so we need to go further up the stack to get the caller.
Profile.lookup(...).func returns the function name (the symbol :foo)
eval(current_module(), Profile.lookup(...)) returns the function object associated with the name :foo in the current_module(). If we modify the definition of function foo to return fobj, then note the equivalence to the foo object in the REPL:
julia> function foo(x)
bt = backtrace()
fobj = eval(current_module(), symbol(Profile.lookup(bt[3]).func))
end
foo (generic function with 1 method)
julia> foo(1) == foo
true
fobj.env.defs returns the first Method entry from the MethodTable for foo/fobj
Base.decl_arg_parts is a helper function (defined in methodshow.jl) that extracts argument information from a given Method.
the rest of the indexing drills down to the name of the argument.
Regarding the restriction that the function have only one method signature, the reason is that multiple signatures will all be listed (see defs.next) in the MethodTable. As far as I know there is no currently exposed interface to get the specific method associated with a given frame address. (as an exercise for the advanced reader: one way to do this would be to modify the address lookup functionality in jl_getFunctionInfo to also return the mangled function name, which could then be re-associated with the specific method invocation; however, I don't think we currently store a reverse mapping from mangled name -> Method).
Note also that (1) backtraces are slow (2) there is no notion of "function-local" eval in Julia, so even if one has the variable name, I believe it would be impossible to actually access the variable (and the compiler may completely elide local variables, unused or otherwise, put them in a register, etc.)
As for the IDE-style introspection use mentioned in the comments: foo.env.defs as shown above is one place to start for "object introspection". From the debugging side, Gallium.jl can inspect DWARF local variable info in a given frame. Finally, JuliaParser.jl is a pure-Julia implementation of the Julia parser that is actively used in several IDEs to introspect code blocks at a high level.
Another method is to use the function's vinfo. Here is an example:
function test(argx::Int64)
vinfo = code_lowered(test,(Int64,))
string(vinfo[1].args[1][1])
end
test (generic function with 1 method)
julia> test(10)
"argx"
The above depends on knowing the signature of the function, but this is a non-issue if it is coded within the function itself (otherwise some macro magic could be needed).
The following code in Julia:
function foo(a::Vector{AbstractString})
end
foo(["a"])
gives the following error:
ERROR: MethodError: no method matching foo(::Array{String,1})
Closest candidates are:
foo(::Array{AbstractString,1}) at REPL[77]:2
Even though the following code runs, as expected:
function foo(a::Vector{String})
end
foo(["a"])
And further, AbstractString generally matches String as in:
function foo(::AbstractString)
end
foo("a")
How can I call a function with a Vector{AbstractString} parameter if I have String elements?
You need to write the function signature like this:
function foo{S<:AbstractString}(a::Vector{S})
# do stuff
end
On Julia 0.6 and newer, it's also possible to write instead
function foo(a::Vector{<:AbstractString})
# do stuff
end
This is a consequence of parametric type invariance in Julia. See the chapter on types in the manual for more details.