[julia-users] strategy design pattern

2016-04-06 Thread Tomas Lycken
Multiple dispatch is actually really well suited for this. The idiomatic 
approach in Julia is quite similar to your c++ example, at least conceptually:

immutable Foo end
immutable Bar end

alg(::Type{Foo}) = println("I'm using foo") 
alg(::Type{Bar}) = println("I'm using bar") 

strategy = Foo # or Bar 
alg(strategy) 

// T 

[julia-users] strategy design pattern

2016-04-06 Thread Igor Cerovsky
Hi,

By exploring Julia I'm curios what would be a best way to implement 
strategy design pattern in Julia. I'm posting a C++ example, for which I 
would like to write equivalent in Julia.
Thanks.

#include 
#include 
#include 

template
void foo_t(const T& t)
{
  std::cout << "I'm using foo_t... \n";
  for (auto a : t)  std::cout << a << '\n';
}

template
void bar_t(const T& t)
{
  std::cout << "I'm usimg bar_t... \n";
  for (auto a : t)  std::cout << a+10 << '\n';
}

template
class alg_t
{
public:
  template
  explicit alg_t(F strategy) : strategy(std::move(strategy)) { }

  void run(const T& t) { strategy(t); }

private:
  std::function strategy;
};

int main()
{
  using VcD = std::vector;
  VcD vec{1., 2., 3.};

  alg_t alg_foo(foo_t);
  alg_foo.run(vec);

  alg_t alg_bar(bar_t);
  alg_bar.run(vec);

  return 0;
}