Scalaz equivalent to forM_

I just played around with ST in scalaz a bit and went to the point where I wanted to use the contents of a passing type to change my STRef . In Haskell, I could do it like this (taken from the Haskell wiki):

 sumST :: Num a => [a] -> a sumST xs = runST $ do n <- newSTRef 0 forM_ xs $ \x -> do modifySTRef n (+x) readSTRef n 

Unfortunately, I could not find an equivalent for forM_ in scalaz. So the question is, how can I do this with a story?

+7
scala functional-programming scalaz
source share
1 answer

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.

+6
source share

All Articles