Reputation: 595
data Error a = OK a | Error String
instance Monad Error where
return = OK
How should i define bind in this case?
>>= : Error a -> (a->error b) -> error b
this is the type of the function bind for this case i hope it's correct.
OK a >>= f = (don't know where to begin need some help)
Error err >>=f = (in this case can i just return error like = Error err)
I also want to know if someone can explain why these usage of seq are problematic. You can find them on slide(page) 10 Usage of seq http://fileadmin.cs.lth.se/cs/Education/EDAN40/lectures/Parallelism.pdf hittendInside xy=someFunc(x 'seq' y) why is this problematic forexamble is it because seq won't return x it will only evaluate it and will only return y. Is this the case in the other two exambles also?
Upvotes: 1
Views: 158
Reputation: 12060
Think of how you would want a pipeline of functions to work
---->f---->g---->h---->
| | |
V V V
Err Err Err
If no error occurs, the data should just be a straight shot through
OK x---->remove OK---->f---->remove OK---->g---->remove OK---->h---->
This can be realized by
OK x >>= f = f x
If at any point you hit an error, the calculation should stop
OK x---->remove OK---->f---->Error (Stop!)
This can be realized by
Error message >>= f = Error message
Incidentally, you don't have to write this, it already exists under the name "Either"
data Either a b = Left a | Right b
The monad was set up so that "Right" passes data through (get it- "Right" means "correct"), and Left stops the data (ie- it is "Error"). If you don't want a message, use "Maybe".
Note that this works a lot like exceptions in Java.
Upvotes: 9
Reputation: 144136
For your OK
case, you have an a
and a function (a -> Error b)
and need to return a value of type Error b
. You can simply apply your function f
to the value a
of your OK
:
OK a >>= f = f a
Error err >>= f = Error err
Upvotes: 1