gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:45:03 26 4
gpt4 key购买 nike

我有这样的数据结构

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])
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

基本上,如果我有一个列表= [Item Apple,Empty,[Item Banana,Empty]]
我希望fmap(++ M)列表返回[Item AppleM .Empty。[Item BananaM,Empty]]

最佳答案

注意数据类型
首先,您的数据类型过于复杂。项目列表确实应该是列表,因此无论如何您都应该在使用列表时定义data ShoppingList' a = ShoppingList' [a]。不需要嵌套购物 list 。
解决您的问题
但是,如果您需要这种方式,那么这是一个解决方案。注意我假设您不需要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上调用它

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

    关于haskell - 在包含单个元素和列表的列表上进行Fmap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54807108/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com