Haskell 映射在 Either 的正确值上

Haskell map on Right value of Either

提问人:confusedandsad 提问时间:10/25/2023 更新时间:10/25/2023 访问量:92

问:

我有一个类型和一个函数Either a [b]f :: (b -> c)

如何使用 on 类型的值来获取?fEither a [b]Either a [c]

Haskell 单子

评论


答:

3赞 AlexSchell 10/25/2023 #1

在上面使用功能。fmap

either 是 Functor 类型类的实例,其中第一个类型是固定的:

data Either a b = Left a | Right b

instance Functor (Either a)
  fmap _ (Left x)  = Left x
  famp f (Right y) = Right (f y)

因此,的 fmap 类型为:Either a

fmap :: (b -> c) -> Either a b -> Either a c

将 fmap 应用于 Either 会导致:a 类型的数据构造函数保持不变,b 类型的数据构造函数应用函数 f 以获取 c 类型。

评论

3赞 Good Night Nerd Pride 10/25/2023
但是 OP 必须写,因为他们的正确类型是 ,对吗?fmap (fmap f) e[b]
0赞 AlexSchell 10/25/2023
是的。List 也是 Functor 类型类的实例(其中 fmap = map)。
0赞 confusedandsad 10/25/2023
谢谢!我缺少的就是这个替身fmap