[Haskell-cafe] Library for overloaded indexing (a la (!))

Nikita Karetnikov nikita at karetnikov.org
Fri Aug 14 06:08:38 UTC 2015


> However, the purpose of this was for syntactic simplicity, which I think
> it's hard to argue Lens provides in this case. "^? ix" isn't exactly
> user-friendly, and it only provides a substitute for "!?", not "!". (Or at
> least, I couldn't figure out how to get "!" behavior cleanly.)

Look at the type:

[1,2,3,4] ^. ix 2 :: (Num a, Monoid a) => a

It typechecks, but the result must be a Monoid that has a Num instance.
There are Product and Sum wrappers for Num (because the identity element
can be either 0 or 1, depending on mappend, which can be + or *).  So,
this works fine:

getSum $ [1,2,3,4] ^. ix 2
=> 3
getSum $ [1,2,3,4] ^. ix 42
=> 0


More information about the Haskell-Cafe mailing list