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.

+3


source to share


1 answer


I think if you're looking for Haskell in Scala, you should definitely take a look at scalaz . He already has replicateM, Monads, Monoids, Monad Transformers, and more

  import scalaz._
  import Scalaz._

  println(Option(1).replicateM(10))

      



Result

Some(List(1, 1, 1, 1, 1, 1, 1, 1, 1, 1))

      

+6


source







All Articles