在Haskell中可遍历

时间:2018-09-12 15:07:26

标签: haskell algebraic-data-types

我正在尝试从Data.Traversable文档中了解示例。

 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

如何应用Leaf <$> f xLeaf不是函数,仍然可以使用。

3 个答案:

答案 0 :(得分:5)

叶是一种功能。

如果您使用GADT语法,这将立即显而易见:

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

答案 1 :(得分:4)

Tree写在GADT Syntax中是有帮助的:

{-# Language GADTs #-}

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

清楚表明Leaf :: a -> Tree a是一个函数。我们可以明确地知道Tree的类型

import Data.Kind

data Tree :: Type -> Type where
  ..

答案 2 :(得分:3)

Leaf是构造函数,因此是函数。在这种情况下,其类型为a -> Tree a。参见haskell wiki

相关问题