optics-core-0.3: Optics as an abstract interface: core definitions

Safe HaskellNone
LanguageHaskell2010

Data.List.Optics

Description

Additional optics for manipulating lists are present more generically in this package.

The Ixed class allows traversing the element at a specific list index.

>>> [0..10] ^? ix 4
Just 4
>>> [0..5] & ix 4 .~ 2
[0,1,2,3,2,5]
>>> [0..10] ^? ix 14
Nothing
>>> [0..5] & ix 14 .~ 2
[0,1,2,3,4,5]

The Cons and AsEmpty classes provide Prisms for list constructors.

>>> [1..10] ^? _Cons
Just (1,[2,3,4,5,6,7,8,9,10])
>>> [] ^? _Cons
Nothing
>>> [] ^? _Empty
Just ()
>>> _Cons # (1, _Empty # ()) :: [Int]
[1]

Additionally, Snoc provides a Prism for accessing the end of a list. Note that this Prism always will need to traverse the whole list.

>>> [1..5] ^? _Snoc
Just ([1,2,3,4],5)
>>> _Snoc # ([1,2],5)
[1,2,5]

Finally, it's possible to traverse, fold over, and map over index-value pairs thanks to instances of TraversableWithIndex, FoldableWithIndex, and FunctorWithIndex.

>>> imap (,) "Hello"
[(0,'H'),(1,'e'),(2,'l'),(3,'l'),(4,'o')]
>>> ifoldMap replicate "Hello"
"ellllloooo"
>>> itraverse_ (curry print) "Hello"
(0,'H')
(1,'e')
(2,'l')
(3,'l')
(4,'o')
Synopsis

Documentation

prefixed :: Eq a => [a] -> Prism' [a] [a] Source #

A Prism stripping a prefix from a list when used as a Traversal, or prepending that prefix when run backwards:

>>> "preview" ^? prefixed "pre"
Just "view"
>>> "review" ^? prefixed "pre"
Nothing
>>> prefixed "pre" # "amble"
"preamble"

suffixed :: Eq a => [a] -> Prism' [a] [a] Source #

A Prism stripping a suffix from a list when used as a Traversal, or appending that suffix when run backwards:

>>> "review" ^? suffixed "view"
Just "re"
>>> "review" ^? suffixed "tire"
Nothing
>>> suffixed ".o" # "hello"
"hello.o"