如何在Haskell中创建一个nullary数据构造函数返回True为null

时间:2017-04-07 16:06:10

标签: haskell null

我有一个代数数据类型,比如说

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

我希望nullTrue节点返回Empty;否则False

例如,

> tree = Empty
> null tree 

现在,这会产生以下错误。

<interactive>:261:1: error:
    • No instance for (Foldable Tree) arising from a use of ‘null’
    • In the expression: null tree
      In an equation for ‘it’: it = null tree

请注意,null确实会为True返回Nothing

> null Nothing
True

1 个答案:

答案 0 :(得分:9)

null需要Foldablenull :: Foldable t => t a -> Bool

的实例

Foldable创建Tree a实例的最简单方法是:

{-# LANGUAGE DeriveFoldable #-}

data Tree a = Node a (Tree a) (Tree a) | Empty deriving Foldable

GHCi

λ > :set -XDeriveFoldable
λ > data Tree a = Node a (Tree a) (Tree a) | Empty deriving Foldable
λ > null Empty
True
λ > null (Node 1 Empty Empty)
False

注意nullTrue返回Nothing的原因是因为Maybe的实例为Foldable

很长的路

而不是使用Haskell的魔法扩展程序获取快捷方式,您可以按照here解释手动编写Foldable实例,它可以归结为:

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

instance Foldable Tree where
  -- The minimal definition is "foldMap" or "foldr", I'm choosing "foldr"
  -- foldr :: (a -> b -> b) -> b -> Tree a -> b
  foldr _ b Empty               = b
  foldr f b (Node a left right) = f a (foldr f (foldr f b right) left)