Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scalaz equivalent to forM_

I was just playing around a bit with ST in scalaz and came to the point, where I wanted to use the contents of a traversable type to modify my STRef. In Haskell I could do that as follows (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 have not been able to find the equivalent for forM_ in scalaz. So the question is, how can I do this with scalaz?

like image 484
drexin Avatar asked Aug 15 '13 14:08

drexin


People also ask

What does :+ mean in Scala?

On Scala Collections there is usually :+ and +: . Both add an element to the collection. :+ appends +: prepends. A good reminder is, : is where the Collection goes. There is as well colA ++: colB to concat collections, where the : side collection determines the resulting type.

What is classOf in Scala?

A classOf[T] is a value of type Class[T] . In other words, classOf[T]: Class[T] . For example: scala> val strClass = classOf[String] strClass: Class[String] = class java. lang. String scala> :t strClass Class[String]

What is r in Scala?

R is a scripting language and environment developed by statisticians for statistical computing and graphics. Like Scala, R supports a functional programming style and provides immutable data types. Scala programmers who learn R will find many familiar concepts, despite the syntactical differences.

What is form in play framework?

Play's form handling approach is based around the concept of binding data. When data comes in from a POST request, Play will look for formatted values and bind them to a Form object. From there, Play can use the bound form to value a case class with data, call custom validations, and so on.


1 Answers

As you probably know, forM_ is a flipped version of mapM_.

You can use traverse and traverse_ (which are implemented in Scalaz), as generalised versions of mapM and mapM_.

As proof, see that Data.Traversable exports its own implementation of mapM, in terms of traverse.

A scalaz version of sumST might 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)
  })

For readers wondering why it is so much more verbose than the haskell version: We must use the Forall trait to represent a rank-2 polymorphic type in Scala. See http://apocalisp.wordpress.com/2011/03/20/towards-an-effect-system-in-scala-part-1/ for a fuller explanation.

like image 198
Ben James Avatar answered Sep 21 '22 17:09

Ben James