在Maybe列表上操作

时间:2018-02-15 00:25:43

标签: haskell functor maybe

我可以每2乘以一个列表:

(* 2) <$> [1, 2, 3]

但我想要乘以Just:

的元素
(* 2) <$> [Just 1, Nothing, Just 3]

错误:

* Non type-variable argument in the constraint: Num (Maybe a)
  (Use FlexibleContexts to permit this)
* When checking the inferred type
    it :: forall a. (Num (Maybe a), Num a) => [Maybe a] Prelude Data.List 

另一次尝试:

fmap (* 2) [Just 1, Nothing, Just 3]

错误:

* Non type-variable argument in the constraint: Num (Maybe a)
  (Use FlexibleContexts to permit this)
* When checking the inferred type
    it :: forall a. (Num (Maybe a), Num a) => [Maybe a]

我尝试了更多的东西:map2,fmap2,map(* 2)map等。

3 个答案:

答案 0 :(得分:9)

一个简单的解决方案是添加另一个fmap以通过Maybe图层:

GHCi> fmap (* 2) <$> [Just 1, Nothing, Just 3]
[Just 2,Nothing,Just 6]

或者,可以使用Compose表示,它允许将两个仿函数层处理为一个:

GHCi> import Data.Functor.Compose
GHCi> (* 2) <$> Compose [Just 1, Nothing, Just 3]
Compose [Just 2,Nothing,Just 6]
GHCi> getCompose $ (* 2) <$> Compose [Just 1, Nothing, Just 3]
[Just 2,Nothing,Just 6]

答案 1 :(得分:6)

你需要映射两次:一次进入列表,第二次进入可能。操作员<$>只会映射一次,您无法使用同一个操作符两次,因此您必须添加对fmap的调用:

fmap (* 2) <$> [Just 1, Nothing, Just 3]

答案 2 :(得分:0)

您可以编写2个fmap函数:

(fmap . fmap) (*2) [Just 1, Nothing, Just 3]

第一个是列表的fmap,第二个是may的fmap。