How to make setters in 2D Array Haskell

后端 未结 2 437
一个人的身影
一个人的身影 2021-01-25 17:50

I currently have a 2D array declared as:

import Data.Array.Unboxed
listArray ((0,0), (9,9)) (replicate 100 \'f\') ∷  UArray (Int, Int) Char

I a

2条回答
  •  盖世英雄少女心
    2021-01-25 18:37

    To access individual elements of an array with lens, you need to use the ix method of the Ixed class, defined in Control.Lens.At. If you define

    fooArray :: UArray (Int, Int) Char
    fooArray = listArray ((0,0), (9,9)) (replicate 100 'f')
    

    then, firing up GHCi,

    > fooArray ^? ix (1,2)
    Just 'f'
    > let fooArray' = fooArray & ix (1,2) .~ 't'
    > fooArray' ^? ix (1,2)
    Just 't'
    

    Note that editing arrays like this is pretty inefficient if the arrays are large; if you need high speed or lots of array edits, you may want to consider a different structure.

    The easiest ways to smash an array flat are the elems function from Data.Array.Unboxed or toList from Data.Foldable. If what those give you is sideways, you can probably patch it up with ixmap.

提交回复
热议问题