Skip to content

Instantly share code, notes, and snippets.

@kozross

kozross/Tree.hs Secret

Created December 24, 2020 02:27
Show Gist options
  • Save kozross/96398bce51eba004df86b24f1a81cb60 to your computer and use it in GitHub Desktop.
Save kozross/96398bce51eba004df86b24f1a81cb60 to your computer and use it in GitHub Desktop.
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE LambdaCase #-}
module Tree where
data Tree a = Leaf | Node (Tree a) a (Tree a)
deriving stock (Eq, Show)
data Direction = L | R
deriving stock (Eq, Show)
insertAt :: [Direction] -> Tree a -> Tree a -> Maybe (Tree a)
insertAt dirs target t = case dirs of
[] -> Just t
(d : ds) -> case target of
Leaf -> Nothing
Node l x r -> case d of
L -> Node <$> insertAt ds l t <*> pure x <*> pure r
R -> Node l x <$> insertAt ds r t
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment