Both the solutions (using immutable type and the earlier solution
suggested by Tamas).
I will check the performance and report back in a week or so.
Thank you,
Devendra
On Thu, Feb 19, 2015 at 09:45:39AM -0500, Isaiah Norton wrote:
Maybe you could use value types (
http://julia.readthedocs.org/en/latest/manual/types/#value-types ),
however, you need to use the latest nighly builds for that. Eg
Something very similar to the first example actually works in 0.3:
immutable Problem{S} end
f(::Type{Problem{1}}, x) = x^2
f(::Type{Problem{2}}, x) = sin(x)
f(Problem{1}, 1)
1
f(Problem{2}, 1)
0.8414709848078965
On Thu, Feb 19, 2015 at 4:24 AM, Tamas Papp <[email protected]> wrote:
Hi,
Maybe you could use value types (
http://julia.readthedocs.org/en/latest/manual/types/#value-types ),
however, you need to use the latest nighly builds for that. Eg
func(::Type{Val{1}}, x) = x^2
func(::Type{Val{2}}, x) = sin(x)
func(Val{1},1) # => 1
func(Val{2},1) # => sin(1)
If you want to stick with 3.6 for now, you could create types for the
cases.
type Case1 end
func(::Type{Case1}, x) = x^2
type Case2 end
func(::Type{Case2}, x) = sin(x)
func(Case1, 1) # => 1
func(Case2, 1) # => sin(1)
Best,
Tamas
On Thu, Feb 19 2015, Devendra Ghate <[email protected]> wrote:
> Hello everyone,
>
> Consider following function:
>
> ~~~
> function funca(problem, x)
> if problem == 1
> return x^2;
> elseif
> problem == 2
> return sin(x);
> end
> end
> ~~~
>
> I have shown only 2 cases. However, there are around 100 cases. These
> `if ... else` statements are being evaluated unnecessarily. If I use
> `switch` structure then it will be faster. But I want to do away with
> these.
>
> Since the arguments and their datatypes remain the same, I don't know
> how to create multiple methods for function.
>
> What is the best strategy to achieve this?
>
> Background:
>
> I am trying to implement a library of ODE solvers for my students.
>
> $y`` + a(x)y` + b(x) = f(x) $
>
> Above function calculates $a(x)$ for a given problem at a specific $x_0$.
>
> So there should various ODE problems defined via the coefficients of
> the derivative terms. My students will then implement various solution
> strategies and compare their performance for these problems. So I need
> to provide
> them with functions `funca` `funcb` `funcf` which give the appropriate
> coefficient depending on the problem.
--
Devendra Ghate