gpt4 book ai didi

haskell - 为什么这个 HasField 实例没有被解析?

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

我正在使用GHC 8.2.1。我有以下模块:

{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Moat (Moat,moat) where

import GHC.Records (HasField(..))

newtype Moat r = Moat r

moat :: r -> Moat r
moat = Moat

instance HasField s r v => HasField s (Moat r) v where
getField (Moat r) = getField @s r

还有另一个:

module Foo (Foo(..)) where

data Foo a = Foo { getDims :: (Int, Int), getData :: [a] }

我的问题是,当我导入两个模块时,我尝试执行以下操作:

{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE DataKinds #-}
import Moat
import Foo
import GHC.Records

oops :: (Int,Int)
oops = getField @"getDims" (moat (Foo (5,5) ['c']))

我收到此错误:

No instance for (HasField "getDims" (Moat (Foo Char)) (Int, Int))
arising from a use of ‘getField’

为什么 HasField 实例没有被解析?

最佳答案

通过启用 {-# LANGUAGE PolyKinds #-} 可以解决该问题在 Moat定义 HasField 的模块实例。

我想这与HasField有关类型类是多类的:

λ :info HasField
class HasField k (x :: k) r a | x r -> a where
getField :: r -> a

这允许我们定义HasField像这样的实例,其中字段选择器是非 Symbol类型:

import GHC.Records
data A = A B
data B = B deriving Show
instance HasField B A B where
getField (A b) = b

在 ghci 中:

λ> getField @B (A B)
B

关于haskell - 为什么这个 HasField 实例没有被解析?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45659190/

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