I'm wondering if there is an identity lens in Haskell. A lens identity
such that if I had a type data MyType = MyType { _myField :: Int }
, then I can do myType ^. identity . myField .~ 2
. There seemed to be one in lens-1.1.1
, but I can't find one in lens-4.19.2
.
Asked
Active
Viewed 299 times
7

Pasindu Muthukuda
- 180
- 1
- 5
-
1I'm no Lens expert, but I don't really see the use of this - and if you do need it, given the definition of the `Lens` type, is it not just `id :: Lens s t s t`? Apologies if I've overlooked something obvious. – Robin Zigmond Jun 23 '20 at 08:57
1 Answers
10
One of the nice things about lens
-style lenses is that they're really just functions. So just as you can use the function composition operator .
on lenses, you can also the identity function id
as a lens, and it acts indeed as an identity-lens in the sense that it “focuses” on the entire data structure.
{-# LANGUAGE TemplateHaskell #-}
import Control.Lens
data MyType = MyType { _myField :: Int }
makeLenses ''MyType
main :: IO ()
main = print $ MyType 37 ^. id . myField

leftaroundabout
- 117,950
- 5
- 174
- 319