Okay, I finally managed to understand the use case of implicit in function parameters and got my type classes working. Let's have a look at my monad type class:
trait Monad[M[_]] extends Functor[M] { self =>
def pure[a](value: a): M[a]
def flatMap[a, b](ma: M[a])(f: a => M[b]): M[b]
}
I created a type class instance for my parser monad (which is just a dummy for now):
case class Parser[a](value: (Unit => a)) {
def >>=[b](f: a => Parser[b])(implicit p: Monad[Parser]): Parser[b] =
p.flatMap(this)(f)
def fmap[b](f: a => Parser[b])(implicit p: Monad[Parser]): Parser[b] =
p.map(this)(f)
}
object Parser {
implicit object MonadInstance extends Monad[Parser] {
override def pure[a](value: a): Parser[a] =
new Parser[a]({ _ => value })
override def flatMap[a, b](ma: Parser[a])(f: (a) => Parser[b]): Parser[b] =
f(ma.value())
override def map[a, b](fa: Parser[a])(f: (a) => b): Parser[b] =
new Parser[b]({ _ => f(fa.value()) })
}
}
I'm just wondering, if I can use the monad instance without having to declare an implicit parameter wherever I use my monads. Is there some way to "import" the functionality globally?
There's a method in Predef called implicitly that is designed for this use case:
def implicitly[T](implicit t: T):T = t
which can be used like this:
val mParser = implicitly[Monad[Parser]]
Original:
In scala, implicits are automatically looked for in the companion objects of the relevant types. So implicitly[Monad[Parser]] ought to just work, because it ought to look in object Parser.
Note that because of the way the interpreter works, it's a bit of a pain to define companion objects in the repl. The easiest thing is to wrap them in an object, or to not start object Parser on a new line (just for the repl).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.