Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any scala library that treat tuples as monads

Is there any scala library that enriches basic scala tuples with monad syntax. Something similar to the Writer monad but adjusted for usage with tuples.

What I look for:

val pair = (2, "as")
pair >>= (a => point(a+1))

should equal to (3, "as"). As well as

for (p <- pair) yield (p+1)
like image 990
ayvango Avatar asked Jun 15 '15 18:06

ayvango


People also ask

Is a tuple a Monad?

One thing I noticed was that Tuple does not have a Monad instance. Which already extremely heavily restricts what we can make the Monad instance be.

Is Scala Option A Monad?

We've used Option as an example above because Scala's Option type is a monad, which we will cover in more detail soon.

What is a benefit of using tuples in Scala?

In Scala, a tuple is a value that contains a fixed number of elements, each with its own type. Tuples are immutable. Tuples are especially handy for returning multiple values from a method.


1 Answers

Yep, Scalaz provides monad instances for tuples (up to Tuple8):

import scalaz.std.anyVal._, scalaz.std.tuple._, scalaz.syntax.monad._

scala> type IntTuple[A] = (Int, A)
defined type alias IntTuple

scala> pair >>= (a => (a+1).point[IntTuple])
res0: (Int, String) = (2,as1)

scala> for (p <- pair) yield (p + 1)
res1: (Int, String) = (2,as1)

(Note that the type alias isn't necessary—it just makes using point a little easier.)

like image 83
Travis Brown Avatar answered Oct 04 '22 00:10

Travis Brown