Felix Ha
Felix Ha

Reputation: 411

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.

Upvotes: 1

Views: 133

Answers (3)

Iceland_jack
Iceland_jack

Reputation: 7014

It helps to write Tree it in GADTSyntax:

{-# Language GADTs #-}

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

which makes it clear that Leaf :: a -> Tree a is a function. We can be explicit about the kind of Tree,

import Data.Kind

data Tree :: Type -> Type where
  ..

Upvotes: 3

Thomas M. DuBuisson
Thomas M. DuBuisson

Reputation: 64740

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

Upvotes: 5

lisyarus
lisyarus

Reputation: 15522

Leaf is a constructor, thus a function. In this case it has type a -> Tree a. See haskell wiki.

Upvotes: 3

Related Questions