Re:How do I modify a variable in Haskell?
by nihils on Tuesday August 15, 2017 @09:43AM
(#15018074)
If you want immutable data structures that simulate the behavior of mutable data structures look into Zippers. In this case, a list zipper.
[ Parent
| on HN ]
Re:How do I modify a variable in Haskell?
by nihils on Thursday August 17, 2017 @11:23AM
(#15037543)
For 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]]