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

标签 haskell records

我正在使用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/

相关文章:

functional-programming - 静态 "extend"是一种没有间接麻烦的记录数据类型

haskell - 避免 Haskell 中的 namespace 污染

common-lisp - 返回字段更改的新结构

带变量的 AWK NR 查找提供额外的输出

windows - 如何在我的 TCP 服务器中获得所需的行为?

haskell - DiffList 的好处

haskell - 在 haskell 中找到树的顶部(根)

haskell - 具有私有(private)类型的类型签名

c# - 如何在 C# 中创建自己的对象,该对象只能具有已定义的有限数量的值,例如像 Haskell 中的 Bools?

F#中的记录列表?