haskell - 如何使用多态类型的setter?
问题描述
在这种情况下如何使用镜头(设置器)?
模块 A:
data Xxx a = Xxx {
_xxxAaa :: Int,
_xxxBbb :: a
}
makeFields ''Xxx
模块 B:
t :: IO Bool
t = do
let n = "aaa" :: String
let xs = [Xxx 0 0, Xxx 1 1] :: [Xxx Int]
ys = [set bbb n $ x | x <- xs]
pure False
错误是:
• Couldn't match type ‘Int’ with ‘[Char]’
arising from a functional dependency between:
constraint ‘HasBbb (Xxx Int) String’ arising from a use of ‘bbb’
instance ‘HasBbb (Xxx a) a’
at .........
顺便说一句,这个技巧适用于元组(它们也是多态的),但不适用于这种类型。
解决方案
HasBbb
生成的类makeFields
不提供类型更改镜头:
ghci> :i HasBbb
class HasBbb s a | s -> a where
bbb :: Lens' s a
{-# MINIMAL bbb #-}
-- Defined at A.hs:14:1
instance HasBbb (Xxx a) a -- Defined at A.hs:14:1
Xxx
将其与- 生成的特定镜头进行对比makeLenses
:
data Xxx a = Xxx {
_xxxAaa :: Int,
_xxxBbb :: a
}
makeFields ''Xxx
makeLenses ''Xxx
ghci> :i xxxBbb
xxxBbb :: Lens (Xxx a1) (Xxx a2) a1 a2 -- Defined at A.hs:15:1
ghci> :t set xxxBbb "aaa" (Xxx 0 0)
set xxxBbb "aaa" (Xxx 0 0) :: Xxx [Char]
推荐阅读
- flutter - 如何在 iOS 设备上运行 Flutter 应用程序?
- javascript - 数据库下拉菜单的默认值
- makefile - Makefile 中的“私有”目标是什么?
- python - Python Statsmodels Holt Winters - 如何使用外生变量进行预测?
- mysql - 重置 Root 密码 Windows 系统 mysql
- javascript - 我有 javascript 代码 getElementsByClassName 它将如何在 php 上运行?
- html - 如何让 Safari 尊重固定定位的插图?
- css - 使用 Angular CLI 缩小 CSS 类名
- php - 会话变量似乎在一小时内到期
- pandas - pandas 按组计算移动平均是错误的