gpt4 book ai didi

haskell - 无模板 haskell 的多态透镜

转载 作者:行者123 更新时间:2023-12-02 17:28:54 24 4
gpt4 key购买 nike

我正在尝试为多种类型创建多态镜头减速(没有模板 haskell)。

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。有没有办法实现这一目标?谢谢。

最佳答案

无需 TH 即可通过 generic-lens 导出镜头。您可以将通用镜头专门用于特定场,并为其指定如下名称。

{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeApplications #-}

import GHC.Generics (Generic)
import Control.Lens (Lens, (^.))
import Data.Generics.Product (HasField(field))

data A = A { _value :: Int } deriving Generic
data B = B { _value :: Int } deriving Generic
data C = C { _value :: String } deriving Generic

value :: HasField "_value" s t a b => Lens s t a b
value = field @"_value"

main :: IO ()
main = print (A 0 ^. value, B 0 ^. value, C "0" ^. value)

关于haskell - 无模板 haskell 的多态透镜,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49593619/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com