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)
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.
We've used Option as an example above because Scala's Option type is a monad, which we will cover in more detail soon.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With