[Haskell-beginners] tuple update
Ertugrul Söylemez
es at ertes.de
Sat Mar 10 02:16:59 CET 2012
Ovidiu Deac <ovidiudeac at gmail.com> wrote:
> Does anybody know if there are any functions like these in the Haskell
> libray?
>
> updateSnd f (x,y) -> (x, f y)
>
> updateFst f (x,y) -> (f x, y)
While the function arrow mentioned by Brent is enough for many purposes,
I just want to have mentioned Edward Kmett's amazing data-lens library,
which provides prefab lenses for tuples:
(3, 5) ^. fstLens = 3
(3, 5) ^. sndLens = 5
(fstLens ^= 4) (3, 5) = (4, 5)
(sndLens ^= 4) (3, 5) = (3, 4)
(fstLens ^%= f) (3, 5) = (f 3, 5)
This is especially useful when your tuple is part of the implicit
argument of a state monad (data-lens-fd package):
access fstLens :: State (a, b) a
-- starting state (3, 5)
fstLens ~= 10 -- (10, 5)
fstLens += 1 -- (11, 5)
fstLens %= negate -- (-11, 5)
focus fstLens $ do
-- Do something with only the fst value here.
Greets,
Ertugrul
--
nightmare = unsafePerformIO (getWrongWife >>= sex)
http://ertes.de/
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 836 bytes
Desc: not available
URL: <http://www.haskell.org/pipermail/beginners/attachments/20120310/4a6589cd/attachment.pgp>
More information about the Beginners
mailing list