How do I pass an enumerated function argument in Julia? - julia

I'm a C and Matlab programmer moving to Julia, and I'm trying to understand how function options should look when passed in.
Sometimes, a function provides different functionality based on an argument passed in with a limited number of different options. In C, it could look something like this:
enum Options{
OPTION_1,
OPTION_2
};
// Other arguments omitted
void foo(..., enum Options option){
switch(option){
case OPTION_1:
// Do something
break;
case OPTION_2:
// Do something else
break;
}
}
In Julia, I am not sure how to structure this. My first attempt used a hierarchy of abstract types, and then a function that accepts a singleton type to make the decision. See the following code:
abstract Options
abstract Option_1 <: Options
abstract Option_2 <: Options
function foo{T<:Options}(..., ::Type{T})
if isa(Option_1, Type{T}
//Do something
elseif isa(Option_2, Type{T})
//Do something else
end
end
However, this seems like a very strange way to approach the problem; creating types just to control function input feels awfully strange.
Also, to clarify, I don't think that this is a solution solvable by general parametric methods in Julia. I am looking for the user to be able to specify a flag (such as run version 1 or version 2), not have different functionality based on input type.
Thanks for the help!

I think parametric methods are actually exactly what you are looking for.
abstract Option_1
abstract Option_2
foo{T<:Options_1}(...) = do_something()
foo{T<:Options_2}(...) = do_something_else()
if there is common code between the two implementations then factor it out into another function and use it in both. Julia doesn't have enums but it does have ways to accomplish the same thing and parametric methods are a perfectly valid way to do so.

If you analyse your question, what you are doing is choosing one of two different functionalities via an argument. Thus you actually have two different functions mixed up inside a single function, and you can (and should) split the two different functionalities out into two different functions.
Once you have done this, it's a short step to realise that the way you decide which function to call is probably (or, at least, often) related to the type of an object. But maybe if you give some more details of your actual use case, we can suggest other alternatives. For example, it might just be a boolean variable that turns on or off a certain type of behaviour.
Note that in Julia v0.4 (the current stable version), you can also use #enum to create enums similar to those available in C: see the NEWS.md file.

Related

Julialang: Enforcing interfaces on Abstract Types

I have been trying to understand the type system for Julialang but some design aspects are still confusing me. I was hoping someone could clarify.
So the question here is about Abstract Types and their concrete implementations. From what I understand Julia Abstract types do not enforce any constraints on their concrete implementations. So there is no guarantee that a method that works on the Abstract type will work on a concrete implementation of that type.
I get that Julia does not use classes or follow inheritance. But I just want to avoid generating all sorts of bugs in my code. If there is a different design paradigm, then could someone please answer question 2 below.
So I have 2 questions.
Is this still the way that the language works? Just to confirm nothing has changed since the blog post.
How do users design their software around this seeming vulnerability?
And example of the issue from the linked post:
abstract type AbstractPerson end
abstract type AbstractStudent <: AbstractPerson end
abstract type AbstractTeacher <: AbstractPerson end
struct Person <: AbstractPerson
name::String
end
struct Student <: AbstractStudent
name::String
grade::Int
hobby::String
end
struct MusicStudent <: AbstractStudent
grade::Int
end
Now if I create some methods on the abstract type.
get_name(x::AbstractPerson) = x.name
p1 = Person("elroy")
get_name(p1)
>"elroy"
So even if MusicStudent is a subtype of AbstractPerson, the MusicStudent DOES NOT have a name attribute. That means that to following behavior is observed.
m1 = MusicStudent(10)
get_name(m1)
ERROR: type MusicStudent has no field name
Stacktrace:
[1] getproperty(::Any, ::Symbol) at ./sysimg.jl:18
[2] get_name(::MusicStudent) at ./In[2]:1
[3] top-level scope at In[13]:2
So the problem here is that Julia allows me to instantiate the type variable m1 with essentially an incomplete constructor. And it only gives me an error when I try to run that function.
So that means if I write a function for the Abstract Type, I can't guarantee every concrete implementation of that type has the same interface. That seems like it will make very fragile code as the developer won't know which types implement which attributes and methods.
Isn't this kind of behavior just a bug in the implementation of the Persons? If you really want the behavior to go without exception you can define a default method:
julia> get_name(p::AbstractPerson) = try return p.name catch y return "" end
get_name (generic function with 1 method)
julia> m1 = MusicStudent(10)
MusicStudent(10)
julia> get_name(m1)
""
I think the underlying struggle may be that in Julia you cannot inherit the data field called "name" as part of the object hierarchy. There is a nice discussion of that genuine issue here (see the mention of the #forward macro):
https://discourse.julialang.org/t/composition-and-inheritance-the-julian-way/11231
The basic answer is that in julia the interface of a method is thought of as the methods that are defined to take an element of that type. AbstractArray for example specifies that implementations should implement getIndex and size. The reason to not make fields part of the interface is that not doing so allows for memory efficient code, since each type can define the methods in the most sensible way. For example if I want to make a type called Bob that is a subtype for all people named bob, I don't want to store his name every time. by using methods, Julia allows much more potential for future expansion in unexpected ways.
Technically this approach loses "safety", but the only way it does is if you write code using fields that might not exist, in which case you will get an error. This type of safety isn't that useful since it just gives you a compile error that slows down development.

Why recommend use ctx as the first parameter?

As the documentation said
Do not store Contexts inside a struct type; instead, pass a Context explicitly to each function that needs it. The Context should be the first parameter, typically named ctx
but I found, in the typical http request handle function, a http.Request object has .Context() method can retrieve the context which http request associate with.
So why recommend to use context as the first parameter in these functions? Is that reasonable in this situation?
I know that is not an absolute rule. But I want to know why the HandlerFunc is func(ResponseWriter, *Request) instead of func(context.Context, ResponseWriter, *Request).
Apparently HandlerFunc breaks this recommendation.
As described in the documentation you quoted above, ctx should be a (very) common argument for many functions. This is similar to the way many functions return an error. The best place for a common argument/return value is either as the first, or last in a list. (Arguably, Go could have chosen to make error always be the first return value--I won't discuss that here).
Since variadic variables may only be the last in the list of function arguments, this leaves the only option for a common argument to be the first one.
I expect this is why ctx is always first.
This pattern is often seen with other variables in Go (and other languages) as well. Any time a common variable is used by a set of related functions, that common variable often comes first in the argument list (or possibly second, after ctx).
Contrary to the advice you quoted, there are libraries that store ctx in a struct, rather than passing it around as the first argument. These are usually (always?) libraries which had to be retro-fitted to use ctx, long after the library contract was set in stone (by the Go 1.x compatibility guarantee).
Generally, you should follow the advice to pass ctx as the first argument, for any new work.

Subtypes of Julia concrete types

In order to practising with Julia, I am implementing a little module containing some fixed step ODE solvers (Euler, Runge Kutta, Bulirsch Stoer) using the iterator interface.
My idea was to use multiple dispatch to apply the correct method of the function next to the particular iterator, however the Euler and Runge Kutta iterator type (actually immutable) old the same data.
So I have to choose between:
create two immutable type identical except for the name or
crate a unique immutable with an additional field (say solving_method) and use branching instead of multiple dispatch to address this issue
Both choices seem clunky to me (in particular the second, because the solving_method field is checked at every iteration).
Reading the online discussions about inheritance in Julia I understood that Julia does not have (and will never have) subtypes of concrete types, meaning that one cannot "add fields" to a parent type in this way.
But why I cannot have subtypes of concrete types just for dispatching purposes?
One idiomatic way to solve this flavor of problem is to create a type that stores parameters or the state of the solver and then have a second immutable to specify the method:
type SolverOptions
# ... step size, error tol, etc.
end
immutable RungeKutta end
immutable Euler end
function solve(problem::ODE, method::RungeKutta, options::SolverOptions)
# ... code here ...
end
function solve(problem::ODE, method::Euler, options::SolverOptions)
# ... code here ...
end
Of course, RungeKutta and Euler need not be empty if you want to store some data in there. This isn't always the best solution (and I can't be sure that it will work in your particular case) but it can help when you are trying to prevent duplication of fieldnames.
Maybe try parametric types?
abstract OdeType
abstract Euler <: OdeType
abstract RK4 <: OdeType
immutable Common{T<:OdeType}
x::Int
end

How can I tell the Closure Compiler not to rename an inner function using SIMPLE_OPTIMIZATIONS?

How can I tell the Closure Compiler not to rename an inner function? E.g., given this code:
function aMeaninglessName() {
function someMeaningfulName() {
}
return someMeaningfulName;
}
...I'm fine with Closure renaming the outer function (I actively want it to, to save space), but I want the function name someMeaningfulName left alone (so that the name shown in call stacks for it is "someMeaningfulName", not "a" or whatever). This despite the fact that the code calling it will be doing so via the reference returned by the factory function, not by the name in the code. E.g., this is purely for debugging support.
Note that I want the function to have that actual name, not be anonymous and assigned to some property using that name, so for instance this is not a duplicate of this other question.
This somewhat obscure use case doesn't seem to be covered by either the externs or exports functionality. (I was kind of hoping there'd be some annotation I could throw at it.) But I'm no Closure Compiler guru, I'm hoping some of you are. Naturally, if there's just no way to do that, that's an acceptable answer.
(The use case is a library that creates functions in response to calls into it. I want to provide a version of the library that's been pre-compressed by Closure with SIMPLE_OPTIMIZATIONS, but if someone is using that copy of the library with their own uncompressed code and single-stepping into the function in a debugger [or other similar operations], I want them to see the meaningful name. I could get around it with eval, or manually edit the compressed result [in fact, the context is sufficiently unique I could throw a sed script at it], but that's awkward and frankly takes us into "not worth bothering" territory, hence looking for a simple, low-maintenance way.)
There is no simple way to do this. You would have to create a custom subclass of the CodingConvention class to indicate that your methods are "local" externs (support for this was added to handle the Prototype library). It is possible that InlineVariables, InlineFunctions, or RemoveUsedVariables will still try to remove the name and would also need to be fixed up.
Another approach is to use the source maps to remap the stack traces to the original source.
read the following section
https://developers.google.com/closure/compiler/docs/api-tutorial3#export
Two options basically, use object['functionName'] = obj.functionName or the better way
use exportSymbol and exportProperty both on the goog object, here is the docs link for that
http://closure-library.googlecode.com/svn/docs/closure_goog_base.js.html
-- edit
ah, i see now, my first answer is not so great for you. The compiler has some interesting flags, the one which might interest you is DEBUG, which you can pass variables into the compiler which will allow you to drop some debugging annotations in via logging or just a string which does nothing since you are using simple mode.
so if you are using closure you can debug against a development version which is just a page built with dependiencies resolved. we also the drop the following in our code
if(DEBUG){
logger.info('pack.age.info.prototype.func');
}

VBScipt: Call builtin functions shadowed by global variables

VBScript on ASP Classic contains an "int" function. (It rounds numbers towards -∞.) Suppose that some excessively "clever" coder has created a global variable named "int". Is there any way to get at the original function? I've tried all manner of workarounds with scoping and dodgy execs, but no dice. I suspect that it is impossible, but I'm hoping that someone will know more about it than I do.
EDIT: Thanks for the responses. Since y'all asked, the global variable, called "Int" (though unfortunately, vbscript is not case-sensitive), is a factory for a class similar to Java's Integer. The default property is essentially a one-arg constructor; i.e. "Int(42)" yields a new IntClass object holding 42. The default property of IntClass in turn simply returns the raw number.
The creator was trying to work around the lack of proper namespaces and static methods, and the solution's actually pretty seamless. Pass in an IntClass where an int is expected and it will automatically trigger the default property. I'm trying to patch the last remaining seam: that external code calling "int" will not round properly (because the constructor uses CLng).
Not that I know of, getref only works on custom functions not on build-ins. I would suggest renaming the custom'int' function and update all references to this custom ones. You can use the search function visual studio (express) or any other tool of your liking for this. Shouldn't be to much work.
I didn't think reserved words would be allowed for function names or variables.
Duncanson's right. Do the pain and rename int. Chances are there are worse things going on than just this.
(why would someone make a global variable named int... that's going to take some thinking)
Or you can use CInt instead on Int
response.write trim(cint(3.14)) + "<br>"
Wrong!!
See NobodyMan comments

Resources