Skip to content

Instantly share code, notes, and snippets.

@coodoo
Created October 25, 2017 09:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coodoo/8554fe0e53fbf877e88c65ffe55c4e16 to your computer and use it in GitHub Desktop.
Save coodoo/8554fe0e53fbf877e88c65ffe55c4e16 to your computer and use it in GitHub Desktop.
list to tree v2
data Item = Item {
sId :: String,
pId :: String,
value :: [Char],
children :: [Item]
} deriving (Show)
list :: [Item]
list = [
Item { sId="1", pId="0", value="1", children=[] },
Item { sId="1-1", pId="1", value="1-1", children=[] },
Item { sId="1-2", pId="1", value="1-2", children=[] },
Item { sId="2", pId="0", value="2", children=[] },
Item { sId="2-1", pId="2", value="2-1", children=[] },
Item { sId="2-2", pId="2", value="2-2", children=[] }]
type Table = M.Map String Item
rootNode = Item { sId="0", pId="-1", value="root node", children=[] }
initTable = M.insert "0" rootNode M.empty
toTable :: [Item] -> Table
toTable xs = foldl (\acc x -> M.insert (sId x) x acc ) initTable xs
foo = evalState (numberTree list) (toTable list)
-- 進入點 --
numberTree :: [Item] -> State Table (State Table Item)
numberTree xs = do
a <- numberNode xs
return a
where
-- State s a
numberNode :: [Item] -> State Table (State Table Item)
-- numberNode [] = Nil
numberNode (x:xs) = do
table <- get
newTable <- return (nNode x table)
put newTable
return (numberNode xs)
nNode :: Item -> Table -> Table
nNode x table =
let parent = fromJust (M.lookup (pId x) table)
in (update parent x )
where
update :: Item -> Item -> Table
update parent current =
let a = parent { children = (sId current) : children parent }
b = M.adjust (\x -> a) (sId parent) table
in b
message itm tbl msg =
itm { value = "Table= " ++ msg ++ (show tbl)}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment