I'd like to learn if my rewrite is worse than the original, less clear or less "idiomatic".
I've found this code that handles updating two dimensional matrixes in Elm:
type alias Matrix a = Array.Array (Array.Array a) type alias Location = (Int, Int) get : Location -> Matrix a -> Maybe a get location m = Array.get (row location) m `andThen` Array.get (col location) set : Location -> a -> Matrix a -> Matrix a set location value m = update location (always value) m update : Location -> (a -> a) -> Matrix a -> Matrix a update location f m = get location m |> Maybe.map ( \current -> Array.get (row location) m |> Maybe.map ( \oldRow -> Array.set (col location) (f current) oldRow |> (\newRow -> Array.set (row location) newRow m) ) |> Maybe.withDefault m ) |> Maybe.withDefault m
I couldn't understand
update at first so I tried to write my own (using my own domain types):
type Player = PlayerOne | PlayerTwo type Slot = Empty | PlayedBy Player type alias Board = Array.Array (Array.Array (Slot)) type alias Position = (Int, Int) get : Board -> Position -> Maybe Slot get board (row, column) = Array.get row board `Maybe.andThen` Array.get column setPosition : Board -> Position -> Player -> Board setPosition board (row, column) player = case get board (row, column) of Nothing -> board Just Empty -> case Array.get row board of Nothing -> board Just oldRow -> let newRow = Array.set column (PlayedBy player) oldRow in Array.set row newRow board Just s -> board
After rewriting I could understand what's going on in the original
update function, but ended up feeling my version's clearer. This is my first day writing Elm so I'm no authority in Elm code clarity.