I am trying to form an infinite grid like data structure by tying the knot.
This is my approach:
import Control.Lens
data Grid a = Grid {_val :: a,
_left :: Grid a,
_right :: Grid a,
_down :: Grid a,
_up :: Grid a}
makeLenses ''Grid
makeGrid :: Grid Bool -- a grid with all Falses
makeGrid = formGrid Nothing Nothing Nothing Nothing
formGrid :: Maybe (Grid Bool) -> Maybe (Grid Bool) -> Maybe (Grid Bool) -> Maybe (Grid Bool) -> Grid Bool
formGrid ls rs ds us = center
where
center = Grid False leftCell rightCell downCell upCell
leftCell = case ls of
Nothing -> formGrid Nothing (Just center) Nothing Nothing
Just l -> l
rightCell = case rs of
Nothing -> formGrid (Just center) Nothing Nothing Nothing
Just r -> r
upCell = case us of
Nothing -> formGrid Nothing Nothing (Just center) Nothing
Just u -> u
downCell = case ds of
Nothing -> formGrid Nothing Nothing Nothing (Just center)
Just d -> d
For some reason, this is not working. As seen here:
*Main> let testGrid = (set val True) . (set (right . val) True) $ makeGrid
*Main> _val $ _right $ _left testGrid
False
*Main> _val $ _left $ _right testGrid
False
*Main> _val $ testGrid
True
Where am I going wrong?
The key insight is: when you
set val True, you're not modifying in place, but creating a copy.makeGridconstructs a grid where everything isFalse, including_left $ _right center. When youset val Trueon thecenter, you're creating a copycenter'whereval center' == True. However, this copy still points to the same_right, which in turn still points to the same_left, in other words:and therefore:
so that: