Related, in Julia0.4 there is also enum: help?> @enum .. @enum EnumName EnumValue1[=x] EnumValue2[=y] Create an :obj:`Enum` type with name ``EnumName`` and enum member values of ``EnumValue1`` and ``EnumValue2`` with optional assigned values of ``x`` and ``y``, respectively. ``EnumName`` can be used just like other types and enum member values as regular values, such as .. doctest:: julia> @enum FRUIT apple=1 orange=2 kiwi=3 julia> f(x::FRUIT) = "I'm a FRUIT with value: $(Int(x))" f (generic function with 1 method) julia> f(apple) "I'm a FRUIT with value: 1"
On Tue, 2015-09-15 at 10:51, Michael Borregaard <mkborrega...@gmail.com> wrote: > Thanks, both, the pattern dispatch package looks useful. I guess the nice > thing about having the possibilities directly in the arguments line is that > it is extremely easy for the user to see the legal possible values of the > argument. > Best, > Michael > > Den tirsdag den 15. september 2015 kl. 10.44.38 UTC+2 skrev Tomas Lycken: >> >> You could also use a fairly common (although it is discouraged in the style >> guide >> <http://docs.julialang.org/en/release-0.4/manual/style-guide/?highlight=style#avoid-confusion-about-whether-something-is-an-instance-or-a-type>) >> >> construct with an “enum type tree”: >> >> abstract SolverMethod >> immutable Spearman end >> immutable Pearson end >> immutable Kendall end >> >> Now, you can define and use your function definition like this: >> >> function foo{Method<:SolverMethod}(x, method::Type{Method}) >> ... >> end >> >> foo(x, Kendall) # solve using Kendall solver >> >> Furthermore, you can leverage multiple dispatch for parts of the function >> that differ based on the solver method. Inside foo, this >> >> if method == "spearman" >> # do spearman specific stuff >> elseif method == "pearson" >> # do pearson specific stuff >> elseif method == "kendall" >> # do kendall specific stuff >> else >> # handle incorrect input >> end >> >> turns into >> >> dostuff(..., method) >> >> # and outside of foo >> function dostuff(..., ::Type{Spearman}) >> # do spearman specific stuff >> end >> function dostuff(..., ::Type{Pearson}) >> # do pearson specific stuff >> end >> function dostuff(..., ::Type{Kendall}) >> # do kendall specific stuff >> end >> >> //T >> >> On Tuesday, September 15, 2015 at 10:32:39 AM UTC+2, Mauro wrote: >> >> No, Julia only dispatches on types not on values. The latter sometimes >>> goes under the name of pattern matching. There is a package for that: >>> https://github.com/toivoh/PatternDispatch.jl >>> >>> On Tue, 2015-09-15 at 10:15, Michael Borregaard <mkborr...@gmail.com> >>> wrote: >>> > Is there a way in julia to restrict the values of arguments to a >>> function, >>> > eg to the contents of a certain vector? >>> > >>> > So, e.g. method in the function >>> > >>> > function foo(x, method::String) ... >>> > >>> > would be constrained to either "spearman", "pearson" or "kendall"? >>> > >>> > Thanks >>> >>> >>