在包含单个元素和列表的列表上进行Fmap

时间:2019-02-21 12:29:02

标签: haskell compiler-errors functor type-mismatch algebraic-data-types

我有一个像这样的数据结构

data ShoppingList a
  = Empty
  | Item a 
  | Listofitems [ShoppingList a]
  deriving (Show)

我正在为此编写fmap

instance Functor ShoppingList where
  fmap f Empty    = Empty
  fmap f (Item i) = Item (f i)
  fmap f (Listofitems [Empty]) = Empty
  fmap f (Listofitems ((Item a):Listofitems [as])) = Listofitems $ (fmap f (Item a)) (fmap f Listofitems [as])

这是我到目前为止所写的内容,但尚未编译,请您帮助我了解这里的问题是什么,解释很不错。 我遇到的两个错误

src\Ml.hs:19:33: error:
    * Couldn't match expected type `[ShoppingList a]'
                  with actual type `ShoppingList a0'
    * In the pattern: Listofitems [as]
      In the pattern: (Item a) : Listofitems [as]
      In the pattern: Listofitems ((Item a) : Listofitems [as])
    * Relevant bindings include
        a :: a (bound at src\Ml.hs:19:30)
        f :: a -> b (bound at src\Ml.hs:19:8)
        fmap :: (a -> b) -> ShoppingList a -> ShoppingList b
          (bound at src\Ml.hs:16:3)
   |
19 |   fmap f (Listofitems ((Item a):Listofitems [as])) = Listofitems $ (fmap f (Item a)) (fmap f Listofitems [as])
   |                                 ^^^^^^^^^^^^^^^^

src\Ml.hs:19:68: error:
    * Couldn't match expected type `b -> [ShoppingList b]'
                  with actual type `ShoppingList b'
    * The function `fmap' is applied to three arguments,
      but its type `(a -> b) -> ShoppingList a -> ShoppingList b'
      has only two
      In the second argument of `($)', namely
        `(fmap f (Item a)) (fmap f Listofitems [as])'
      In the expression:
        Listofitems $ (fmap f (Item a)) (fmap f Listofitems [as])
    * Relevant bindings include
        f :: a -> b (bound at src\Ml.hs:19:8)
        fmap :: (a -> b) -> ShoppingList a -> ShoppingList b
          (bound at src\Ml.hs:16:3)
   |
19 |   fmap f (Listofitems ((Item a):Listofitems [as])) = Listofitems $ (fmap f (Item a)) (fmap f Listofitems [as])
   |                                                                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

基本上,如果我有一个列表= [苹果项目,空,[香蕉项目,空]] 我想要fmap(++ M)列表返回[Item AppleM .Empty。[Item BananaM,Empty]]

1 个答案:

答案 0 :(得分:2)

有关数据类型的说明

首先,您的数据类型过于复杂。项目列表确实应该是一个列表,因此无论如何,您都应该在使用列表时定义data ShoppingList' a = ShoppingList' [a]。无需嵌套购物清单。

您的问题的解决方案

但是,如果您需要那样的话,这是一个解决方案。注意我假设您不需要ShoppingLists列表,因为您的数据定义中已经有一个列表。所以你可以打电话

--fmap :: (a -> b) -> ShoppingList a -> ShoppingList b
fmap _ Empty = Empty
fmap f (Item i) = Item (f i)
fmap f (Listofitems ls) = Listofitems $ map (fmap f) ls


>>fmap (++ "M") $ Listofitems [Item "Apple", Empty, Listofitems [Item "Banana", Empty]]
Listofitems [Item "AppleM",Empty,Listofitems [Item "BananaM",Empty]]

注意:

  • 您需要在字符串两边加上引号,
  • 您需要在Listofitems上调用它

还请记住,如果需要性能,字符串附加操作对于长字符串来说效率不高