gpt4 book ai didi

haskell - 具有特化规则的函数依赖

转载 作者:行者123 更新时间:2023-12-02 18:56:54 25 4
gpt4 key购买 nike

我想写一个specialization rewrite rule对于 Megaparsec 组合器,以便仅当输入类型为 ByteString 时才触发规则。

{-# LANGUAGE ExplicitForAll #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}

import Data.Void
import Text.Megaparsec
import qualified Data.ByteString as B

combin :: forall e s m a. (MonadParsec e s m)
=> m a
-> m a
combin = label "String generic"

combinByteString :: forall e s m a. (MonadParsec e s m, s ~ B.ByteString)
=> m a
-> m a
combinByteString = label "ByteString specialized"

main = do
parseTest (combin empty :: Parsec Void String String) ""
parseTest (combin empty :: Parsec Void B.ByteString String) ""

{-# NOINLINE combin #-}
{-# NOINLINE combinByteString #-}
{-# RULES "combin/ByteString" combin = combinByteString #-}

当我尝试构建它时,它失败了:

$ cabal v2-run
Build profile: -w ghc-8.6.5 -O1
Main.hs:25:40: error:
• Couldn't match type ‘s’ with ‘B.ByteString’
arising from a functional dependency between constraints:
‘MonadParsec e B.ByteString m’
arising from a use of ‘combinByteString’ at Main.hs:25:40-55
‘MonadParsec e s m’
arising from the RULE "combin/ByteString" at Main.hs:25:11-55
‘s’ is a rigid type variable bound by
the RULE "combin/ByteString"
at Main.hs:25:11-55
• In the expression: combinByteString
When checking the transformation rule "combin/ByteString"
|
25 | {-# RULES "combin/ByteString" combin = combinByteString #-}

MonadParsec的输入流类型参数s有一个functional dependencyMonad 参数 m 上。

class (Stream s, MonadPlus m) => MonadParsec e s m | m -> e s where

这是一个用于尝试构建的 specialize.cabal 文件。

cabal-version:       >=1.10
name: specialize
version: 0.1.0.0
build-type: Simple

executable specialize
main-is: Main.hs
build-depends: base >= 4
,megaparsec
,bytestring
default-language: Haskell2010

如果成功,输出应如下所示:

1:1:
|
1 | <empty line>
| ^
expecting String generic
1:1:
|
1 | <empty line>
| ^
expecting ByteString specialized

建议?

最佳答案

此规则有效,但仅适用于 GHC 8.8.1,不适用于 GHC 8.6.5。

{-# LANGUAGE TypeApplications #-}

{-# RULES "combin/ByteString" forall e. forall.
combin @e @B.ByteString = combinByteString @e @B.ByteString
#-}

此规则适用于 GHC 8.6.5 和 8.0.2

{-# RULES "combin/ByteString"
forall (pa :: ParsecT e B.ByteString m a).
combin @e @B.ByteString @(ParsecT e B.ByteString m) @a pa =
combinByteString @e @B.ByteString @(ParsecT e B.ByteString m) @a pa
#-}

关于haskell - 具有特化规则的函数依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58560791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com