考虑这种类型:
data Vec3 = Vec3 {_x, _y, _z :: Int}
我有一些函数都采用相同的输入,并且可能无法计算字段:data Input
getX, getY, getZ :: Input -> Maybe Int
我可以编写一个函数来尝试所有这三个字段构造函数:v3 :: Input -> Maybe Vec3
v3 i = liftA3 Vec3 (getX i) (getY i) (getZ y)
但是必须通过 i
有点烦人输入大约三遍。函数本身就是一个应用仿函数,因此可以替换 foo x = bar (f x) (g x) (h x)
与 foo = liftA3 bar f g h
.在这里,我的
bar
是 liftA3 Vec3
,所以我可以写v3' :: Input -> Maybe Vec3
v3' = liftA3 (liftA3 Vec3) getX getY getZ
但这有点粗俗,当我们以这种方式处理组合应用程序时(((->) Input)
和 Maybe
),就会出现 Compose
newtype 来处理这种事情。有了它,我可以写v3'' :: Input -> Maybe Vec3
v3'' = getCompose go
where go = liftA3 Vec3 x y z
x = Compose getX
y = Compose getY
z = Compose getZ
好的,这并不是一个很好的字符节省,但我们现在使用一个组合仿函数而不是两个,这很好。我想我可以使用 coerce
为我赢回一些角色:毕竟,x
只是 getX
的新类型包装器,对于其他领域也是如此。所以我想我可以强制liftA3
接受三个Input -> Maybe Vec3
而不是接受三个 Compose ((->) Input) Maybe Vec3
:v3''' :: Input -> Maybe Vec3
v3''' = getCompose go
where go = coerce liftA3 Vec3 getX getY getZ
但这不起作用,产生错误消息:tmp.hs:23:14: error:
• Couldn't match representation of type ‘f0 c0’
with that of ‘Input -> Maybe Int’
arising from a use of ‘coerce’
• In the expression: coerce liftA3 Vec3 getX getY getZ
In an equation for ‘go’: go = coerce liftA3 Vec3 getX getY getZ
In an equation for ‘v3'''’:
v3'''
= getCompose go
where
go = coerce liftA3 Vec3 getX getY getZ
|
23 | where go = coerce liftA3 Vec3 getX getY getZ
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
我不明白为什么不。我可以写coerce getX :: Compose ((->) Input) Maybe Int
,这很好。通常可以强制一个函数以使其强制其参数或返回类型,如coerce ((+) :: Int -> Int -> Int) (Max (5::Int)) (Min (8::Int)) :: Sum Int
我实际上可以写出所有coerce
s 单独:v3'''' :: Input -> Maybe Vec3
v3'''' = getCompose go
where go = liftA3 Vec3 x y z
x = coerce getX
y = coerce getY
z = coerce getZ
那么为什么不能liftA3
自己被迫接受getX
而不是 coerce getX
,允许我使用 v3'''
?
最佳答案
如果您将应用仿函数提供给 liftA3
,然后进行以下类型检查:
v3' :: Input -> Maybe Vec3
v3' = coerce (liftA3 @(Compose ((->) Input) Maybe) Vec3) getX getY getZ
在 coerce liftA3
没有任何注释,就无法推断使用什么应用仿函数 liftA3
和。这些甚至都没有提到类型 Compose
.也可以是 ReaderT Input Maybe
, Kleisli Maybe Input
,另一种类型的非法实例或更奇特的东西。在
getCompose (coerce liftA3 _ _ _)
(您的最后一次尝试),getCompose
不约束 liftA3
(coerce
的“内部”),因为 getCompose
是 coerce
的“外部” .它要求 liftA3
的结果类型可强制为 Compose ((->) Input) Maybe Vec3
,但它可能仍然不等于那个。
关于haskell - 为什么 `coerce` 不隐式地将 Compose 应用于这些函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70259338/