相当于“ _1”样式元组镜头快捷方式的数据类?

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

[根据其documentation,Haskell的lens库的_1为元组提供了一个镜头。

对于数据记录,还有其他一些功能,例如makeLenses,它们会根据记录的字段名称自动生成镜头。

[不幸的是,我正在处理没有命名字段的数据类,这意味着makeLenses对我来说似乎出现了。这让我感到奇怪。 _1似乎很方便,但隐含在其文档中,似乎不适用于数据类。是否有与之相似的便利水平?

> :set -package lens
> import Control.Lens
> (1,2) ^. _1
1
> data Bar = Bar String deriving Show
> bar = Bar "abc"
> bar ^. _1

<interactive>:271:1: error:
    • Non type-variable argument in the constraint: Field1 Bar Bar b b
      (Use FlexibleContexts to permit this)
    • When checking the inferred type
        it :: forall b. Field1 Bar Bar b b => b

添加FlexibleContexts扩展名,我却遇到了另一个错误:

bar ^. _1

<interactive>:6:1: error:
    • No instance for (Field1 Bar Bar () ()) arising from a use of ‘it’
    • In the first argument of ‘print’, namely ‘it’
      In a stmt of an interactive GHCi command: print it
haskell lens lenses
1个回答
5
投票

Field1具有默认的通用实现,因此您可以自己添加一个实例:

{-# LANGUAGE DeriveGeneric #-}
import GHC.Generics (Generic)

data Bar = Bar String deriving (Show, Generic)

instance Field1 Bar Bar String String

generic-lens也提供相同的功能,而无需该样板实例。 _1被称为position @1(从Data.Generics.Product(.Positions)起)。

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