【发布时间】:2018-08-15 17:01:04
【问题描述】:
给定以下数据类型:
data Tree a =
Branch (Tree a) (Tree a)
| Leaf a deriving (Eq, Show)
还有以下 Functor 实例:
instance Functor Tree where
fmap f (Leaf a) = Leaf $ f a
fmap f (Branch t1 t2) = Branch (fmap f t1) (fmap f t2)
如何最好地实现这棵树的 Applicative 实例? 我想出了:
instance Applicative Tree where
pure = Leaf
Leaf f <*> t = f <$> t
Branch t1 t2 <*> Leaf a = t1 <*> Leaf a
Branch t1 t2 <*> Branch t3 t4 = Branch (t1 <*> t3) (t2 <*> t4)
即使它可以编译,我对这个实现也很怀疑。
我不知道这个Branch (Leaf (+1)) (Leaf (+2)) <*> Leaf 7是应该返回Leaf 8(找到最接近的函数来应用)还是复制并返回Branch (Leaf 8) (Leaf 9)。
【问题讨论】:
标签: haskell binary-tree applicative