As you probably know, forM_ is an inverted version of mapM_ .
You can use traverse and traverse_ (which are implemented in Scalaz) as generic versions of mapM and mapM_ .
As proof, see that Data.Traversable exports its own mapM implementation in terms of traverse .
The sumST version of sumST may look like this:
def sumST[S, A](as: List[A])(implicit A: Numeric[A]): ST[S, A] = for { n <- newVar(A.zero) _ <- as.traverseU(a => n.mod(A.plus(_, a))) m <- n.read } yield m def sum[A : Numeric](as: List[A]): A = runST(new Forall[({type λ[S] = ST[S, A]})#λ] { def apply[S] = sumST[S, A](as) })
Readers wonder why this is much more verbose than the haskell version: we should use the Forall attribute to represent the rank 2 polymorphic type in Scala. See http://apocalisp.wordpress.com/2011/03/20/towards-an-effect-system-in-scala-part-1/ for a more complete explanation.
Ben james
source share