You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Haskell中如何对Either a [b]的Right值应用函数f得到Either a [c]

如何将函数应用于Either a [b]得到Either a [c]

对于类型Either a [b]的值,结合函数f :: b -> c,可以通过以下几种方式得到Either a [c]类型的结果:

1. 嵌套使用fmap(推荐)

Haskell中Either e和列表[]都是Functor实例,因此可以直接嵌套调用fmap:

-- 示例:将Int转为String的函数
f :: Int -> String
f = show

-- 示例Either值
input :: Either String [Int]
input = Right [1, 2, 3]

-- 执行转换
output :: Either String [String]
output = fmap (fmap f) input
-- 结果:Right ["1", "2", "3"]
  • 逻辑:外层fmap作用于Either结构,仅处理Right分支;内层fmap f将函数f逐个应用到列表的每个元素上,把[b]转为[c]。
  • 如果输入是Left值(比如Left "error"),转换后会直接保留Left "error",不会做任何修改。

2. 显式模式匹配实现

如果你需要更直观地控制分支逻辑,可以手动写一个函数处理两种情况:

mapEitherList :: (b -> c) -> Either a [b] -> Either a [c]
mapEitherList _ (Left err) = Left err
mapEitherList f (Right xs) = Right (fmap f xs)

这个函数的行为和fmap (fmap f)完全一致,只是把分支逻辑显式写了出来,适合需要自定义额外逻辑的场景。

内容的提问来源于stack exchange,提问作者confusedandsad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 22:18:15