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

问题描述 投票:4回答:1

在下面的代码中,

{-# 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)的内置实例。还是这样吗?或者实施是否偏离提案?

haskell record
1个回答
0
投票

在(至少当前)基础上,IsLabel没有OverloadedLabels实例(参见讨论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

© www.soinside.com 2019 - 2024. All rights reserved.