Recreating Haskell `replicateM` behavior in Scala
I'm trying to learn how to do monadic code in Scala, but I'm missing Haskell's ability to constrain types belonging to typeclasses that declare the type of a function.
For example, I'm trying to write something like replicateM
from Control.Monad
in Scala. Without caring about type annotations, it would be something like this:
def replicateM(n: Int)(x: M[A]): M[List[A]] = n match {
case 0 => map(x => List())
case _ => for {
head <- x
tail <- replicateM(n-1)(x)
} yield head: tail
}
(I can see that this might not be a more efficient implementation, it's just an easy way to write it).
Where am I stumbling: How do I annotate the types correctly here? What type is M? How to restrict M to only the types that have flatMap
defined on them? I feel like I can do this with traits, but I'm not sure how to do it.
source to share