Need some help writing a Haskell function that takes a string and creates a binary tree. Need some help from someone with a little better Haskell experience to fill in some holes for me and describe why because this is a learning experience for me.
I'm given a tree encoded in a single string for a project in Haskell (Example **B**DECA
). The star denotes a node any other character denotes a Leaf. I'm trying to fill this data structure with the information read in from input.
data Trie = Leaf Char | Branch Trie Trie
I'm more of a math and imperative programming guy so I made the observation that I can define a subtree by parsing from left to right. A proper tree will have 1 more character than *
. Mathematically I would think of a recursive structure.
If the first character is not a *
the solution is the first character. Else the solution is a Branch where the subbranches are feed back into the function where the left Branch is the first set of characters where Characters out number *
's and the right Branch is everything else.
constructTrie :: String -> Trie
constructTrie x = if x !! 1 == '*' then
let leftSubtree = (first time in drop 1 x where characters out number *'s)
rightSubtree = (rest of the characters in the drop 1 x)
in Branch constructTrie(leftSubtree) constructTrie(rightSubtree)
else Leaf x !! 1
Mostly I need help defining the left and right subtree and if there is anything wrong with defining it this way.