Skip to content

Instantly share code, notes, and snippets.

@coodoo
Created October 25, 2017 04:47
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/43a5cedb900d810a01825143e7708dad to your computer and use it in GitHub Desktop.
Save coodoo/43a5cedb900d810a01825143e7708dad to your computer and use it in GitHub Desktop.
convert list to tree structure
data Item = Item {
sId :: String,
pId :: String,
value :: [Char],
children :: [String]
} 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
-- 先將 list 轉成 map
toTable :: [Item] -> Table
toTable xs = foldl (\acc x -> M.insert (sId x) x acc ) initTable xs
entry = numberTree list (toTable list)
r1 = mapM_ print entry -- 印出 table 內容
r2 = M.lookup "2-1" entry -- 查找 "2-1" 這個 item
numberTree xs table = do
foldl (\a x -> nNode x a) table 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment