Вопрос

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.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top