在haskell中找到树的顶部(根)

时间:2014-02-04 12:18:06

标签: haskell

我有一棵这样的树:

data Tree a
  = Empty
  | Leaf a
  | Node a (Tree a) (Tree a) String
  deriving (Show)

我需要一个找到树顶的函数。我写了这个:

root :: Tree a -> a
root (Leaf a) = a
root (Node a _ _ _) = a

完美有效,但是当我有一棵空树时,我有一条错误信息。

如果我添加

root Empty = Empty 

我再次出错,因为它没有返回a类型的值。我该怎么办?

1 个答案:

答案 0 :(得分:11)

a构造函数的情况下,Empty没有合理的值。在这种情况下,类型Maybe完全符合您的需要:合理值或无值。因此,以下将是实现您的功能的惯用方法:

root :: Tree a -> Maybe a
root (Leaf a) = Just a
root (Node a _ _ _) = Just a
root _ = Nothing

您可以使用functors, applicative functors and monads轻松地将此功能与库的其他功能组合在一起。 E.g:

functionOnPlainA :: a -> a
functionOnPlainA = error "implement me"

-- So simply we can lift our plain function to work on values of type `Maybe`.
-- This is a Functor example.
functionOnMaybeA :: Maybe a -> Maybe a
functionOnMaybeA = fmap functionOnPlainA

-- Because the above is so simple, it's conventional to inline it,
-- as in the following:
applyFunctionOnPlainAToResultOfRoot :: Tree a -> Maybe a
applyFunctionOnPlainAToResultOfRoot tree = fmap functionOnPlainA $ root tree

-- And here is an example of how Monads can serve us:
applyRootToMaybeTree :: Maybe (Tree a) -> Maybe a
applyRootToMaybeTree maybeTree = maybeTree >>= root