我正在尝试创建一个多态透镜声明(不使用模板哈斯克尔)来处理多个类型。
module Sample where
import Control.Lens
data A = A {_value:: Int}
data B = B {_value:: Int}
data C = C {_value:: String}
value = lens _value (\i x -> i{_value=x}) -- <<< ERROR
但是我收到了以下错误信息:
Ambiguous occurrence ‘_value’
It could refer to either the field ‘_value’,
defined at library/Sample.hs:5:13
or the field ‘_value’, defined at
library/Sample.hs:4:13
or the field ‘_value’, defined at
library/Sample.hs:3:13
|
6 | value = lens _value (\i x -> i{_value=x}) -- <<< ERROR
| ^^^^^^
所以,目标是让 value
镜头适用于 A、B、C 三种类型。有没有办法实现这一点?
谢谢。
b
函数依赖于a
,即{-# LANGUAGE FunctionalDependencies #-}
class HasValue a b | a -> b
。或者,在我看来更好的方式是,将字段类型改为关联类型族:{-# LANGUAGE FunctionalDependencies #-}
class HasValue a where {type ValueField a :: *; value :: Lens' a (ValueField a)}
。 - leftaroundabout