Carl Dong
Carl Dong

Reputation: 1299

Scala generic Monad function?

In scala, how would I write a generic function for a sort of monad if I want to use pure(or something like that)? Like this signature in Haskell:

f :: Monad m => a -> m b

The thing is, There is not a generic pure or return that I found, so I cannot really pack up the a into the monad m.

Upvotes: 0

Views: 207

Answers (1)

Peter Neyens
Peter Neyens

Reputation: 9820

Scalaz has point (in scalaz.syntax.applicative) and it also has the alias pure (so you could replace point with pure below) :

import scalaz._, Scalaz._

1.point[Option]  // Option[Int] = Some(1)
1.point[List]    // List[Int] = List(1)

It is a little more difficult for a monad with multiple type parameters, in which case you need to use a type lambda or a type alias.

1.point[({ type λ[α] = String \/ α })#λ] // \/[String,Int] = \/-(1)

type ErrorOr[A] = String \/ A
1.point[ErrorOr]                         // ErrorOr[Int] = \/-(1)

1.point[({ type λ[α] = Reader[Int, α] })#λ]

You could simplify the type lambdas by using the kind projector compiler plugin :

1.point[String \/ ?]
1.point[Reader[Int, ?]]

Upvotes: 2

Related Questions