(How) is it possible to represent monads in Scala in a generic way (like the Monad typeclass in Haskell)? Is it somehow possible to define a trait Monad for this purpose?
(How) is it possible to represent monads in Scala in a generic way (like
Share
You could try something like this:
You would of course define similar implicit objects for any other monad your heart desires. In Haskell terms, you can think of
Monadlike the typeclass andMonadicOptionas a particular instance of that type class. ThemonadicSyntaximplicit conversion simply demonstrates how this typeclass could be used to allow the use of Scala’sfor-comprehensions with anything which satisfies theMonadtypeclass.Generally speaking, most things in the Scala standard library which implement
flatMapare monads. Scala doesn’t define a genericMonadtypeclass (though that would be very useful). Instead, it relies on a syntactic trick of the parser to allow the use offor-comprehensions with anything which implements the appropriate methods. Specifically, those methods aremap,flatMapandfilter(orforeachandfilterfor the imperative form).