无法推断出因使用“to”而产生的(逆变f)

问题描述 投票:0回答:1

我是 Haskell 的新手,我正在尝试

transform
从如下所示的遍历中获得的值

startedAt :: Traversal' Object Int
startedAt = ix "at" 
          . (_Integral 
            `failing`  _String . to timeComponent._Right 
            `failing` _String ._Integral)

timeComponent :: Text -> Either String Int
timeComponent t = ...

我收到此错误

Could not deduce (Contravariant f) arising from a use of ‘to’
      from the context: Applicative f
        bound by the type signature for:
                   startedAt :: Traversal' Object Int
        at SomeModule/Optics.hs:80:1-34
      Possible fix:
        add (Contravariant f) to the context of
          the type signature for:
            startedAt :: Traversal' Object Int
    • In the first argument of ‘(.)’, namely ‘to timeComponent’
      In the second argument of ‘(.)’, namely ‘to timeComponent . _Right’
      In the second argument of ‘(.)’, namely
        ‘to timeComponent . _Right’

在代码的其他部分,开发人员已经在做

doSomething :: Object -> First Int
doSomething l = First $ <same-code-as-above> 

正如您所看到的,当我内联它时它可以工作,但是当我将它移动到像上面这样的单独光学元件时,它会抛出错误...

Ps:还有一个疑问,什么时候应该将类型指定为 Traversal 而不是 Prism?

haskell functional-programming haskell-lens haskell-optics
1个回答
0
投票

您的光学器件是

Fold Object Int
,而不是
Traversal' Object Int
。如果您将类型签名写为:

startedAt :: Fold Object Int

然后它会输入检查。

根本的问题是

to f
产生
Getter
,而不是
Traversal'
,当你用遍历(如
ix "at"
)和吸气剂(如
to timeComponent
)组成一个光学器件时,你会得到一个折叠。

© www.soinside.com 2019 - 2024. All rights reserved.