OverloadedLabels:记录数据类型上没有 IsLabel 实例

OverloadedLabels: No instance for IsLabel on record data type

在下面的代码中,

{-# 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) 的内置实例。现在还是这样还是执行上和提案有偏差?

在(至少当前)基地中没有 OverloadedLabelsIsLabel 实例(参见讨论 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