Last active
November 27, 2015 03:05
-
-
Save parsonsmatt/f0fb2e6b35d446234ad4 to your computer and use it in GitHub Desktop.
This file contains 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
module Rose where | |
import Data.List (findIndex) | |
data Tree a = Node { value :: a, getSubForest :: [Tree a] } deriving Show | |
insertPath :: (Eq a ) => [a] -> Tree a -> Tree a | |
insertPath [] tree = tree | |
insertPath (x:xs) (Tree a subForest) = Tree a modifiedSubForest | |
where | |
maybeIndex = | |
findIndex (\node -> value node == x) subForest | |
subtree = | |
case maybeIndex of | |
Just index -> | |
subForest !! index | |
Nothing -> | |
Node x [] | |
modifiedSubForest = | |
case maybeIndex of | |
Just index -> | |
replaceAt index (insertPath xs subtree) subForest | |
Nothing -> | |
insertPath xs subtree : subForest | |
replaceAt :: Int -> a -> [a] -> [a] | |
replaceAt 0 a [] = [a] | |
replaceAt _ _ [] = [] | |
replaceAt 0 a (_ : xs) = a : xs | |
replaceAt n a (x : xs) = x : replaceAt (n - 1) a xs |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment