[Haskell-cafe] The (!) operation
byorgey at seas.upenn.edu
Thu Mar 8 21:43:33 CET 2012
On Thu, Mar 08, 2012 at 07:53:48PM +0100, Christopher Done wrote:
> On 8 March 2012 18:32, Anthony Cowley <acowley at seas.upenn.edu> wrote:
> > Perhaps Data.Key meets your needs?
> > http://hackage.haskell.org/packages/archive/keys/2.1.2/doc/html/Data-Key.html
> Ah, perhaps indeed. Thanks!
> On 8 March 2012 19:12, Francesco Mazzoli <f at mazzo.li> wrote:
> > The type signature that you wrote is very generic and doesn't help in
> > introducing effects while retrieving the indexed value, which I imagine is
> > what you wanted to do.
> Because Maybe is already a monad and it's nice to fail in the monad of
> choice, e.g. if I'm in the list monad I get empty list instead, or if
> I'm in the Result monad from JSON it'll fail in there. ‘Course "fail"
> is suboptimal and MonadError might be better.
Monads have nothing to do with failure. Instead of Monad you would
want to use something like MonadZero or MonadError. However, these
are also suboptimal because in monads which carry extra information
about the failure (i.e. anything other than  or Maybe), the lookup
function now has to make up an error message, when it almost certainly
it doesn't know enough to give a good one. This is why the use of
Maybe is encouraged: Maybe is the *initial* instance of MonadZero, so
you can map from it to failure in whatever monad you happen to be
using. Instead of being an annoyance this is encouraged style,
because in doing the conversion *you* get to pick a meaningful error
message. For example
fromMaybe (throwError WidgetNotFound) (lookup foo blah)
fromMaybe (Left "Missing wurble specification: flozz") (lookup foo blah)
More information about the Haskell-Cafe