I have a construct, let's call it Container. It, as you might guess, is a container for another object, with some headers (a simple map). There are two instances of the container, a success container, or a failed container.
I have a function defined on container, called
flatMap(f: Container[T]=> Container[U]): Container[U]
Pretty familiar right, except unlike a 'real' monad, it's from M[A]->M[B], rather than A->M[B]. This is because I want the mapping functions to have access to all the fields of the container.
Now there's no real problem with this, except it doesn't follow the definitions for a monad and so it doesn't work with for comprehensions as a generator.
Any suggestions, other than changing the flatMap definition, or am I just SoL :)
If you're going from M[A]
to M[B]
then all you want is map
class Container[A](stuff: A){
def map[B](f: A => B): Container[B] = new Container(f(stuff))
}
The function flatMap
really is for functions of type A => M[B]
to be able to work on a type of M[A]
. Hence,
class Container[A](stuff: A){
def map[B](f: A => B): Container[B] = new Container(f(stuff))
def flatMap[B](f: A => Contains[B]): Container[B] = f(stuff)
}
so you really don't need flatMap
in your definition at all.
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.