3 ms·
If you want immutable data structures that simulate the behavior of mutable data structures look into Zippers. In this case, a list zipper.
by nihils 9y ago
If you want immutable data structures that simulate the behavior of mutable data structures look into Zippers. In this case, a list zipper.
- nihils 9y agoFor example, this problem of modifying the diagonal of a matrix can be solved quite easily: type Zipper a = ([a],[a]) cursorOnDiagonal :: [[Int]] -> [Zipper Int] cursorOnDiagonal matrix = map (\(n,x) -> splitAt n x) (zip [0..(length matrix)-1] matrix) flipToOneAtCursor :: [Zipper Int] -> [Zipper Int] flipToOneAtCursor = map (\(ys,x:xs) -> (ys,1:xs)) backToList :: [Zipper Int] -> [[Int]] backToList = map (\(ys,xs) -> ys ++ xs) If matrix == [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]], then: backToList . flipToOneAtCursor . cursorOnDiagonal $ matrix == [[1,0,0,0],[0,1,0,0],[0,0,1,0],[0,0,0,1]]