LesleyLai / elm-grid / Grid

Grids are 2-dimensional arrays. The elements in a grid must have the same type.

Definition


type Grid a

Grid represents immutable 2 dimensional arrays.

Initializeation

initialize : Basics.Int -> Basics.Int -> (Basics.Int -> Basics.Int -> a) -> Grid a

Initializes a Grid. initialize w h f creates a grid of width w, height 'h', with the elements at (i j) initialized to the result of (f i j).

repeat : Basics.Int -> Basics.Int -> a -> Grid a

Creates an grid with a given width and height, filled with a default element.

Just (repeat 2 2 'a') == fromList[['a', 'a'], ['a', 'a']]

fromList : List (List a) -> Maybe (Grid a)

Creates a grid from a List of List. If the input list is not well formed, this function will returns Nothing. fromList [['e','l','m'], ['e','l','m'], ['e','l','m']] -- A 3x3 (Maybe grid)

fromList [['e','l','m'],
          ['e','l','m'],
          ['e','l']] == Nothing

Queries

get : ( Basics.Int, Basics.Int ) -> Grid a -> Maybe a

Returns Just the element at the index or Nothing if the index is out of range.

let grid = fromList [['a','b','c'],
                     ['d','e','f'],
                     ['g','h','i']]
in
Maybe.andThen (get 1 2) grid == Just 'h'
Maybe.andThen (get -1 2) grid == Nothing

width : Grid a -> Basics.Int

Gets the width of the Grid

height : Grid a -> Basics.Int

Gets the height of the Grid

rows : Grid a -> Array (Array a)

Gets the an array of rows of the grid

Manipulate

set : ( Basics.Int, Basics.Int ) -> a -> Grid a -> Grid a

Set the element at a particular index. Returns an updated grid. If the index is out of range, the grid is unaltered.

let grid = fromList [['a','b','c'],
                     ['d','e','f'],
                     ['g','h','i']]
    grid2 = fromList [['a','b','c'],
                      ['d','e','f'],
                      ['g','a','i']]
in
Maybe.andThen (set 1 2 'a') grid == grid2

Transform

map : (a -> b) -> Grid a -> Grid b

Applies a function on every element in an array.

Maybe.map (map sqrt) (fromList [[1,4], [9,16]]) == fromList [[1,2], [3,4]]

indexedMap : (Basics.Int -> Basics.Int -> a -> b) -> Grid a -> Grid b

Applies a function on every element with its index as first and second arguments.

indexedMap (\x y e -> (x, y, e)) (repeat 2 2 1)
-- [[(0,0,1),(1,0,1)],
--  [(0,1,1),(1,1,1)]]

foldl : (a -> b -> b) -> b -> Grid a -> b

Reduces the grid from the left.

foldr : (a -> b -> b) -> b -> Grid a -> b

Reduces the grid from the right.