【问题标题】:Applicative instance for non-empty leafy tree in HaskellHaskell中非空多叶树的应用实例
【发布时间】: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)) &lt;*&gt; Leaf 7是应该返回Leaf 8(找到最接近的函数来应用)还是复制并返回Branch (Leaf 8) (Leaf 9)

【问题讨论】:

    标签: haskell binary-tree applicative


    【解决方案1】:

    即使它可以编译,我对这个实现也很怀疑。我不知道这个 Branch (Leaf (+1)) (Leaf (+2)) Leaf 7 应该返回 Leaf 8(找到最接近的函数来应用)还是复制并返回 Branch (Leaf 8) (Leaf 9)

    合理的实例应遵循Applicative functor laws,其中之一是:

    u <*> pure y = pure ($ y) <*> u -- Interchange
    

    Branch t1 t2 <*> Leaf a
    

    应该与:

    pure ($ a) <*> Branch t1 t2
    

    但是根据这个实现:

    Leaf f <*> t = f <$> t
    

    应该等于:

    ($ a) <$> Branch t1 t2
    

    我。 e

    Branch (fmap ($ a) t1) (fmap ($ a) t2)
    

    因此,在 Branch (Leaf (+1)) (Leaf (+2)) &lt;*&gt; Leaf 7 的特定情况下,它应该返回:

    Branch (Leaf 8) (Leaf 9)
    

    【讨论】:

    • 感谢您的回答! ($a) 是什么意思?
    • 我提供的链接(关于法律)包含以下信息: ($ y) 是将 y 作为参数提供给另一个函数的函数。 en.wikibooks.org/wiki/Haskell/…
    • @MMacphail ($ a)(\f -&gt; f a) 相同,该函数采用函数f 并将其应用于a
    • @MMacphail,更一般地说,如果*&amp;* 是一个运算符,则(*&amp;* y)(称为运算符部分)与\x -&gt; x *&amp;* y 相同。在这种情况下,运算符是$,定义为f $ a = f a。你也可以在另一边使用运算符:(x *&amp;*) = \y -&gt; x *&amp;* y
    • @IgorDrozdov 作者代码中的最后一个等式是否正确?也就是说,Branch t1 t2 &lt;*&gt; Branch t3 t4 = Branch (t1 &lt;*&gt; t3) (t2 &lt;*&gt; t4) ... 直觉上感觉不对,Branch t1 t2 &lt;*&gt; t = Branch (t1 &lt;*&gt; t) (t2 &lt;*&gt; t) 感觉更好,但我想不出任何例子或证据来支持这种感觉。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多