简体   繁体   English

fmap在我的数据类型列表上不起作用

[英]fmap does not work on list of my datatype

I have defined my datatype as: 我已将数据类型定义为:

data MyMaybe a = Lust a | Lothing deriving (Show,Eq,Ord,Functor, Foldable)

When I type fmap (+3) Lust 4 it gives me the correct answer: Lust 7 当我输入fmap (+3) Lust 4它给了我正确的答案: Lust 7

But when I type fmap (+3) [Lust 4, Lust 5] it does not work and I get the follwoing error: 但是,当我输入fmap (+3) [Lust 4, Lust 5]它不起作用,并且出现以下错误:

Non type-variable argument in the constraint: Num (MyMaybe a)

Please tell me what to do resolve this error. 请告诉我该怎么办才能解决此错误。

fmap (+3) works for a single MyMaybe in this case. 在这种情况下, fmap (+3)适用于单个 MyMaybe If you want to map a function over a list, you map that function. 如果要在列表上映射功能,则可以映射该功能。 Let's give fmap (+3) a name: 让我们给fmap (+3)命名:

myMaybePlus3 :: Num a => MyMaybe a -> MyMaybe a
myMaybePlus3 = fmap (+3)

We can now see that it only works for a single MyMaybe . 现在我们可以看到它仅适用于单个MyMaybe We can use map (or fmap ) to use it for a list: 我们可以使用map (或fmap )将其用于列表:

map myMaybePlus3 [Lust 4, Lust 5]

But due to referential transparency, we can also simply write 但是由于参照透明性,我们也可以简单地编写

map (fmap (+3)) [Lust 4, Lust 5]

So all you were missing was an additional (f)map . 因此,您所缺少的只是一张附加的(f)map

Look at the type of fmap : 查看fmap的类型:

fmap :: Functor f => (a -> b) -> f a -> f b

When you do 当你做

fmap (+3) [Lust 4, List 5]

You are using fmap on a list [] , so fa in this case is Num b => [MyMaybe b] 您正在列表[]上使用fmap ,因此在这种情况下, faNum b => [MyMaybe b]

The implementation of fmap on a list is to map all elements of the list. fmap在列表上的实现是映射列表的所有元素。 In this case, the elements are MyMaybe's . 在这种情况下,元素是MyMaybe's But you can't apply +3 on your MyMaybe s because it isn't a Num . 但是您不能在MyMaybe上应用+3 ,因为它不是Num If you want you can do: 如果您愿意,可以执行以下操作:

fmap (fmap (+3)) [Lust 4, List 5]

This will apply the function fmap (+3) on each element of the list. 这会将功能fmap (+3)应用于列表的每个元素。


You can use ghci to examine types of simple expressions, for example: 您可以使用ghci检查简单表达式的类型,例如:

Prelude> :t fmap (+3)
fmap (+3) :: (Functor f, Num b) => f b -> f b

Shows that the argument to fmap (+3) must be a functor of some Num 表明fmap (+3)的参数必须是某些Num fmap (+3)函数

In your code you are traversing through the list (using fmap ) and are trying to apply (+3) to all elements, but your list elements are of type Num a => MyMaybe a . 在代码中,您正在遍历列表(使用fmap ),并尝试将(+3)应用于所有元素,但是列表元素的类型为Num a => MyMaybe a

You need to apply fmap twice. 您需要两次应用fmap Once for traversing the list as you did, and another to traverse each element inside the list which, again, has the type Num a => MyMaybe a . 一次用于遍历列表,另一遍用于遍历列表中的每个元素,该元素再次具有Num a => MyMaybe a

So the code needs to be: 所以代码需要是:

fmap (fmap (+3)) [Lust 4, Lust 5]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM