haskell - 为什么 `coerce` 不隐式地将 Compose 应用于这些函数?

标签 haskell applicative

考虑这种类型:

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 .
在这里,我的barliftA3 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 的“内部”),因为 getComposecoerce 的“外部” .它要求 liftA3 的结果类型可强制为 Compose ((->) Input) Maybe Vec3 ,但它可能仍然不等于那个。

关于haskell - 为什么 `coerce` 不隐式地将 Compose 应用于这些函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70259338/

相关文章:

haskell - 两个非仿函数可以组成一个仿函数吗?

haskell - 如何在纯函数中跳过不必要的 IO?

haskell - optparse-应用回溯

Haskell 与 ContT、callCC 的混淆,当

haskell - 如何使用 Scotty/wai 在代理后面记录真实 IP 地址

haskell - 将命令行参数分配给变量

haskell - 应用程序组成,单子(monad)不组成

haskell - 我应该如何遍历类型对齐的序列?

c# - F# vs Haskell vs Lisp——学习哪种语言?

haskell - "Pattern match"并递归封闭类型族中的类型以进行类型相等证明