From efd33ff05ecab0b567831022d837ba1c1a40f0c4 Mon Sep 17 00:00:00 2001 From: Joscha Date: Sun, 9 Feb 2020 22:43:03 +0000 Subject: [PATCH] Implement replacing subnodes via path --- src/Forest/Node.hs | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/src/Forest/Node.hs b/src/Forest/Node.hs index 9c56de1..992dc03 100644 --- a/src/Forest/Node.hs +++ b/src/Forest/Node.hs @@ -7,12 +7,13 @@ module Forest.Node -- * Node NodeId , Node(..) - , hasChildren , emptyNode , initialNode + , hasChildren + , mapChildren , applyId , applyPath - , mapChildren + , replaceAt -- * Path , Path(..) , localPath @@ -56,23 +57,29 @@ instance ToJSON Node where instance FromJSON Node where parseJSON = genericParseJSON nodeOptions -hasChildren :: Node -> Bool -hasChildren = not . Map.null . nodeChildren - emptyNode :: T.Text -> Bool -> Bool -> Bool -> Bool -> Node emptyNode text edit delete reply act = Node text edit delete reply act Map.empty initialNode :: Node initialNode = emptyNode "Loading..." False False False False +hasChildren :: Node -> Bool +hasChildren = not . Map.null . nodeChildren + +mapChildren :: (NodeId -> Node -> a) -> Node -> [a] +mapChildren f node = map (uncurry f) $ Map.toAscList $ nodeChildren node + applyId :: NodeId -> Node -> Maybe Node applyId nodeId node = nodeChildren node Map.!? nodeId applyPath :: Path -> Node -> Maybe Node applyPath (Path ids) node = foldM (flip applyId) node ids -mapChildren :: (NodeId -> Node -> a) -> Node -> [a] -mapChildren f node = map (uncurry f) $ Map.toAscList $ nodeChildren node +replaceAt :: Node -> Path -> Node -> Node +replaceAt childNode (Path []) _ = childNode +replaceAt childNode (Path (x:xs)) node = + let newChildren = Map.adjust (replaceAt childNode $ Path xs) x $ nodeChildren node + in node{nodeChildren = newChildren} {- Path -}