Skip to content

Instantly share code, notes, and snippets.

@parsonsmatt
Last active November 27, 2015 03:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parsonsmatt/f0fb2e6b35d446234ad4 to your computer and use it in GitHub Desktop.
Save parsonsmatt/f0fb2e6b35d446234ad4 to your computer and use it in GitHub Desktop.
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