Skip to content

Instantly share code, notes, and snippets.

@tanakh
Created October 31, 2012 05:44
Show Gist options
  • Select an option

  • Save tanakh/3985084 to your computer and use it in GitHub Desktop.

Select an option

Save tanakh/3985084 to your computer and use it in GitHub Desktop.
Lens study
import Control.Category
import Prelude hiding (id, (.))
data Lens a b
= Lens
{ get :: a -> b
, set :: b -> a -> a
}
modify :: Lens a b -> (b -> b) -> a -> a
modify l f a = set l (f (get l a)) a
instance Category Lens where
id =
Lens id const
l . m =
Lens (get l . get m) (modify m . set l)
_fst :: Lens (a, b) a
_fst = Lens fst (\a (_, b) -> (a, b))
_snd :: Lens (a, b) b
_snd = Lens snd (\b (a, _) -> (a, b))
_lines :: Lens String [String]
_lines = Lens lines (const . unlines)
main :: IO ()
main = do
print $ set (_snd >>> _fst) 777 (1, (2, 3))
-- print $ set (_snd >>> _fst) "hoge" (1, (2, 3)) -- compile error
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment