Haskell filling list with missing elements -


i'm trying write function

fill::int->int->[(int, int, int)]->[(int, int, int)]  fill width height board = ... 

that "fills" given board ( in single (int, int, int) triple on board first 2 ints coordinates, third 1 value @ field ) missing ones (with third coordinate set 0), e.g.:

let x = fill 3 3 [(1,2,2),(1,3,5),(3,2,3)] 

should result in

x = [(1,1,0),(1,2,2),(1,3,5),(2,1,0),(2,2,0),(2,3,0),(3,1,0),(3,2,3),(3,3,0)]. 

is there nice function used here, or complicated double recursion in order?

a direct way may (with ~o(n^2) cost)

fill :: int -> int -> [(int, int, int)] -> [(int, int, int)]  fill b defaults = [(x, y, maybe 0 id (search x y defaults)) | x <- [1..a], y <- [1..b]]            search _ _ [] = nothing                  search x y ((u,v,k):rs) | x == u && y == v = k                                          | otherwise        = search x y rs 

but prefer split key/values (with ~o(n log n) cost)

import data.map hiding (foldr)  -- using key/value fill' :: int -> int -> [((int, int), int)] -> [((int, int), int)] fill' b defaults = assocs                    $ foldr (\(k, v) m -> insertwith (+) k v m) empty                    $ defaults ++ [((x,y),0) | x <- [1..a], y <- [1..b]] 

example

main =      print $ fill 3 3 [(1,2,2),(1,3,5),(3,2,3)]     print $ fill' 3 3 [((1,2),2),((1,3),5),((3,2),3)] 

yours default values 0, if not, must replace (+) on insertwith. can think how?


Comments