In the code below,
{-# LANGUAGE OverloadedLabels #-}
module Foo where
data R = R { x :: Int }
g :: Int
g = #x (R { x = 1 })
Run Code Online (Sandbox Code Playgroud)
I expected this to type-check, but instead I get:
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})
Run Code Online (Sandbox Code Playgroud)
Given the Overloaded Record Fields proposal, I expected there to be a built-in instance of IsLabel "x" (R -> Int). Is this still the case or does the implementation deviate from the proposal?
在(至少当前)基础中没有IsLabel实例OverloadedLabels(参见此处的讨论)。您可能想要使用一些定义孤立实例的库,例如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
Run Code Online (Sandbox Code Playgroud)