2次元リストを座標付き1次元リストに変換する
恐らく[(a, Row, Col)]はあまり筋の良い構造ではないので使い道がないだろうけど、一応メモ
code:hs
type Row = Int
type Col = Int
withCoordinates :: a -> (a, Row, Col)
withCoordinates matrix = [ (x, r, c)
| (r, row) <- zip 0.. matrix
, (c, x) <- zip 0.. row
]
リスト内包表記 (hs)の練習としてもちょうど良さそう
リスト内包表記を使わずに書いた例
code:hs
withCoordinates :: a -> (a, Row, Col)
withCoordinates matrix = concatMap withRow (zip 0.. matrix)
where
withRow :: (Col, a) -> (a, Row, Col)
withRow (c, row) = zipWith (\r x -> (x,r,c)) 0.. row
使用例
code:hs
main :: IO ()
main = do
let matrix = 1, 2, 3], 4, 5, 6, [7, 8, 9
print (withCoordinates matrix)
-- 出力: (1,0,0),(2,0,1),(3,0,2),(4,1,0),(5,1,1),(6,1,2),(7,2,0),(8,2,1),(9,2,2)