Array indexing: improved safety with modular arithmetic

From HaskellWiki
Revision as of 05:04, 19 January 2019 by Atravers (talk | contribs) (Created page with "Category:Proposals Instead of an error being triggered if an array access is outside its bounds: <pre> Prelude Data.Array> array (0, 1) (zip [0, 1] [False, True]) ! 2 *...")

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search


Instead of an error being triggered if an array access is outside its bounds:

Prelude Data.Array> array (0, 1) (zip [0, 1] [False, True]) ! 2
*** Exception: Ix{Integer}.index: Index (2) out of range ((0,1))

use the given index modulo the array's length:

Prelude Data.Array> array (0, 1) (zip [0, 1] [False, True]) ! 2
False

As an added benefit, accessing the end elements of an array would be simplified:

Prelude Data.Array> [ array (0, 25) (zip [0..25] ['a'..'z']) ! n | n <- [-1, -2 .. -8] ]
"zyxwvuts"

Atravers 04:54, 19 January 2019 (UTC)