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
?
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With