在下面的代码中,

{-# LANGUAGE OverloadedLabels #-}
module Foo where

data R = R { x :: Int }

g :: Int
g = #x (R { x = 1 })

我希望这能进行类型检查,但我得到:
foo.hs:7:5: error:
    • No instance for (GHC.OverloadedLabels.IsLabel "x" (R -> Int))
        arising from the overloaded label ‘#x’
        (maybe you haven't applied a function to enough arguments?)
    • In the expression: #x
      In the expression: #x (R {x = 1})
      In an equation for ‘g’: g = #x (R {x = 1})

考虑到Overloaded Record Fields提议,我希望有一个IsLabel "x" (R -> Int)的内置实例。还是这样吗?还是实现方案偏离了提案?

最佳答案

在(至少当前)基础上没有IsLabelOverloadedLabels实例(请参见Discussion here)。
您可能要使用一些定义孤立实例的库,例如generic-lens
当然,您可以自己定义:

{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE ScopedTypeVariables #-}

import GHC.Records
import GHC.OverloadedLabels

instance HasField x r a => IsLabel x (r -> a) where
  fromLabel = getField @x

关于haskell - 重载标签: No instance for IsLabel on record data type,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60698141/

10-10 14:13