haskell - 可以部分应用仿函数吗

标签 haskell types functor

我正在尝试为以下类型实现fmap:

data Tree a = Leaf a | Node a (Tree a) (Tree a) | Empty deriving (Eq,Show)
instance Functor Tree where
        fmap _ Empty=Empty
        fmap f (Leaf x)=Leaf (f x)
        fmap f (Node t left right)=Node (f t) left right

我不断收到类型不匹配错误:

错误

* Couldn't match type `a' with `b'
      `a' is a rigid type variable bound by
        the type signature for:
          fmap :: forall a b. (a -> b) -> Tree a -> Tree b
        at Monad.hs:8:9-12
      `b' is a rigid type variable bound by
        the type signature for:
          fmap :: forall a b. (a -> b) -> Tree a -> Tree b
        at Monad.hs:8:9-12
      Expected type: Tree b
        Actual type: Tree a

为什么我会收到此错误,但当我也将 fmap 应用于子节点时,它编译时没有问题:

fmap f (Node t left right) = Node (f t) (fmap f left) (fmap f right)

这是否意味着 Tree 中的所有 a-s 必须以某种方式变成 b-s ?我只处理第一种情况中的非仿函数? ^

最佳答案

Does it mean that all a-s within the Tree must somehow become b-s ? and i am only dealing with the non-functor one in the first case ? ^

是的,没错。您正在尝试实现 fmap::(a -> b) -> Tree a -> Tree b,但是当您编写时:

fmap f (Node t left right) = Node (f t) left right

您正在尝试使用参数 f t::b, left 调用 Node::b -> Tree b -> Tree b -> Tree b::树a,以及右::树a。将 Tree a 转换为 Tree b 的唯一方法是通过 fmap f::Tree a -> Tree b,即为什么这样:

fmap f (Node t left right) = Node (f t) (fmap f left) (fmap f right)

按预期工作。

关于haskell - 可以部分应用仿函数吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55701842/

相关文章:

haskell - 树与否(Haskell 类型理解)

performance - IORef 和 STRef 的编译

oracle - 如何在 Oracle 数据库中将列的数据类型从 varchar2 更改为数字

c++ - 何时在 lambda 上使用仿函数

haskell - 为什么应该在函数式编程中使用应用仿函数?

haskell - Threepenny-GUI:拖放 - 访问 DragData

json - 是否可以使用 Text.JSON 在 haskell 中创建嵌套的 JSON 对象?

C++ (C++11) 中的函数对象

haskell - 基于类型级别谓词的实例?

types - 类型错误F# “The type ” int“不匹配…”