Search code examples
haskellalgebraic-data-types

Traversable in Haskell


I'm trying to understand the example from the Data.Traversable documentation.

 data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a)

instance Traversable Tree where
    traverse f Empty        = pure Empty
    traverse f (Leaf x)     = Leaf <$> f x -- confusion

How it is possible to apply Leaf <$> f x. Leaf is not a function and it is still possible to use it.


Solution

  • Leaf is a function.

    If you use GADT syntax this becomes immediately apparent:

    data Tree a where
        Empty :: Tree a
        Leaf  :: a -> Tree a
        Node  :: Tree a -> a -> Tree a -> Tree a