Shouldn't it be function foo(x, method::SolverMethod) ... end foo(x, Kendall) # solve using Kendall solver ? if isa(method, Spearman) # do spearman specific stuff elseif isa(method, Pearson) # do pearson specific stuff elseif isa(method, Kendall) # do kendall specific stuff else # handle incorrect input end
On Tuesday, September 15, 2015 at 10:44:38 AM UTC+2, Tomas Lycken wrote: > > 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 >> >> >