Created
January 3, 2017 03:21
-
-
Save sayoder/3849cf9c99120fb20093bc95ec00ad3e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Data.List (elemIndex) | |
import Data.Maybe (fromJust) | |
--similar to /u/Ashandalar's definition, but more general just for kicks | |
----- | |
data Node a = Node a [Node a] deriving (Show) | |
-- Wrapper around makeNode. Converts the list to index/value pairs | |
-- so it's easier to work with. So, [4,0,0,-1,3] becomes . | |
-- Given [4,0,0,-1,3], returns (makeNode [(0,4),(1,0),(2,0),(3,-1),(4,3)] (3,-1)) | |
----- | |
fromParentIxs :: [Int] -> Node Int | |
fromParentIxs ls = makeNode zippedLs (fromJust $ elemIndex (-1) ls, -1) | |
where zippedLs = zip [0..] ls | |
-- Simply create a node given a tuple. To create the child list, we just map this | |
-- function over the subset of tuples for which the "parent pointer" (a.k.a. the | |
-- second item in the tuple) is the index of this node. Notice we don't even need | |
-- the "parent pointer" of the node we're currently working on. | |
----- | |
makeNode :: Eq a => [(a,a)] -> (a,a) -> Node a | |
makeNode [] (i, _) = Node i [] | |
makeNode ls (i, _) = Node i children | |
where children = map (makeNode ls) childTuples | |
childTuples = filter (\(_,parent) -> parent == i) ls |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment