Common practice for higher-order-polymorphism in scala

Posted by raichoo on Stack Overflow See other posts from Stack Overflow or by raichoo
Published on 2010-04-05T12:15:03Z Indexed on 2010/04/05 16:23 UTC
Read the original article Hit count: 368

Filed under:
|
|

Hi,

I'm trying to grasp higher-order-polymophism in scala by implementing a very basic interface that describes a monad but I come across a problem that I don't really understand.

I implemented the same with C++ and the code looks like this:

#include <iostream>

template <typename T>
class Value {
private:
  T value;
public:
  Value(const T& t) {
    this->value = t;
  }

  T get() {
    return this->value;
  }
};

template < template <typename> class Container >
class Monad {
public:
  template <typename A> Container<A> pure(const A& a); 
};

template <template <typename> class Container>
  template <typename A>
Container<A> Monad<Container>::pure(const A& a) {
  return Container<A>(a);
}

int main() {
  Monad<Value> m;
  std::cout << m.pure(1).get() << std::endl;
  return 0;
}

When trying to do the same with scala I fail:

class Value[T](val value: T)

class Monad[Container[T]] {
  def pure[A](a: A): Container[A] =
    Container[A](a)
}

object Main {
  def main(args: Array[String]): Unit = { 
    val m = new Monad[Value]
    m.pure(1)
  }
}

The compiler complains about:

[raichoo@lain:Scala]:434> scalac highorder.scala
highorder.scala:5: error: not found: value Container
    Container[A](a)
    ^
one error found

What am I doing wrong here? There seems to be a fundamental concept I don't seem to understand about scala typeconstructors.

Regards, raichoo

© Stack Overflow or respective owner

Related posts about scala

Related posts about polymorphism