You perform pattern matching. For example if you want the first child, you can use:
firstChild :: Tree a -> Maybe (Tree a)
firstChild (Node (h:_)) = Just h
firstChild _ = Nothing
Here we wrap the answer in a Maybe
type, since it is possible that we process a Leaf x
or a Node []
, such that there is no first child.
Or we can for instance obtain the i-th item with:
iThChild :: Int -> Tree a -> Tree a
iThChild i (Node cs) = cs !! i
So here we unwrap the Node
constructor, obtain the list of children cs
, and then perform cs !! i
to obtain the i-th child. Note however that (!!) :: [a] -> Int -> a
is usually a bit of an anti-pattern: it is unsafe, since we have no guarantees that the list contains enough elements, and using length
is an anti-pattern as well, since the list can have infinite length, so we can no do such bound check.
Usually if one writes algorithms in Haskell, one tends to make use of linear access, and write total functions: functions that always return something.