haskell - 如何将多态函数应用于 Either 的两侧?
问题描述
我试过这个:
type TestT = Either Int Float
testM :: (a -> a) -> TestT -> TestT
testM f (Left x) = Left (f x)
testM f (Right x) = Right (f x)
但它不起作用,有没有办法做到这一点?我环顾四周,所有类似的东西都非常复杂和有限。
错误消息,根据要求:
Main.hs:101:28: error:
• Couldn't match expected type ‘a’ with actual type ‘Int’
‘a’ is a rigid type variable bound by
the type signature for:
testM :: forall a. (a -> a) -> TestT -> TestT
at Main.hs:100:1-35
• In the first argument of ‘f’, namely ‘x’
In the first argument of ‘Left’, namely ‘(f x)’
In the expression: Left (f x)
• Relevant bindings include
f :: a -> a (bound at Main.hs:101:7)
testM :: (a -> a) -> TestT -> TestT (bound at Main.hs:101:1)
解决方案
一种方法是使用 Bifunctor:
Prelude> :m +Data.Bifunctor
Prelude Data.Bifunctor> bimap show show (Left 3)
Left "3"
Prelude Data.Bifunctor> bimap show show (Right 'x')
Right "'x'"
Prelude Data.Bifunctor>
推荐阅读
- javascript - 清除输入文本失败
- android - 列表中包含 Jetpack 中项目的适合/包裹宽度的任何想法 compose
- css - Blazor 问题,关于基于属性的宽度百分比
- java - 如何在java中打印一个arraylist并删除它的重复项
- java - 如何将绘图图上的 x 和 y 坐标转换为 GUI 上的像素
- authlib - 使用 authlib 设置知名 url 的任何示例?
- google-sheets - IF 和 CountIF 公式,你能改变重复单元格的第一个值吗?
- amazon-web-services - 键包含点时是否可以设置映射?
- python-3.x - Sqlalchemy 查询外键
- sql - BigQuery 谷歌分析自动化问题