Pasindu Muthukuda
Pasindu Muthukuda

Reputation: 178

Haskell Identity Lens

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.

Upvotes: 7

Views: 358

Answers (1)

leftaroundabout
leftaroundabout

Reputation: 120711

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

Upvotes: 10

Related Questions