Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between ix and element in the Lens library of Haskell

In Haskell's lens library, ix and element both take an Int an can be used e.g. to read or write a list element at some index, like this

ghci> [1..10] ^? ix 4
Just 5
ghci> [1..10] & ix 4 .~ 1
[1,2,3,4,1,6,7,8,9,10]

and similarly:

ghci> [1..10] ^? element 4
Just 5
ghci> [1..10] & element 4 .~ 1
[1,2,3,4,1,6,7,8,9,10]

What is the difference between element and ix?

like image 705
Stephan Avatar asked Jan 22 '15 10:01

Stephan


1 Answers

With ix you can index not only by number, but by e.g. key in the Maps. The element index in Traverse order.

λ> let m = Map.fromList [("foo", 'f'), ("bar", 'b')]
λ> m ^? ix "foo"
Just 'f'

λ> m ^? element 0 -- Map is ordered container!
Just 'b'

The difference is even more obvious with e.g. IntMap

λ> let im = IntMap.fromList [(1, "one"), (2, "two")]
λ> im ^? ix 1
Just "one"
λ> im ^? element 1
Just "two"
like image 53
phadej Avatar answered Sep 23 '22 20:09

phadej