微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Haskell Parsec令牌键入条件

如何解决Haskell Parsec令牌键入条件

考虑最小化的代码

module Parser where

import Text.ParserCombinators.Parsec
import Text.Parsec.Pos

onetokenP f = token show (\_ -> initialPos "Dummy") f
onetoken t = token show (\_ -> initialPos (show t)) 
                  (\t' -> if t == t' then Just () else nothing)

我收到错误消息:

Parser.hs:8:1: error:
    • Non type-variable argument
        in the constraint: Text.Parsec.Prim.Stream
                             s Data.Functor.Identity.Identity a1
      (Use FlexibleContexts to permit this)
    • When checking the inferred type
        onetokenP :: forall u s a a1.
                     (Show a1,Text.Parsec.Prim.Stream s Data.Functor.Identity.Identity a1) =>
                     (a1 -> Maybe a) -> Text.Parsec.Prim.Parsec s u a

Parser.hs:9:1: error:
    • Non type-variable argument
        in the constraint: Text.Parsec.Prim.Stream
                             s Data.Functor.Identity.Identity a
      (Use FlexibleContexts to permit this)
    • When checking the inferred type
        onetoken :: forall u s a.
                    (Eq a,Show a,Text.Parsec.Prim.Stream s Data.Functor.Identity.Identity a) =>
                    a -> Text.Parsec.Prim.Parsec s u ()

我违反了哪种键入条件?

按照@amalloy的建议进行了重写:

onetokenP f = token showTok posFromTok testTok
 where
     showTok (pos,t) = show t
     posFromTok (pos,t) = initialPos "Dummy"
     testTok (pos,t) = f t
onetoken x = token showTok posFromTok testTok
 where 
     showTok (pos,t) = initialPos (show t)
     testTok (pos,t) = if x == t then Just () else nothing

解决方法

将您的函数与the example in the documentation for token进行比较:

 mytoken x
   = token showTok posFromTok testTok
   where
     showTok (pos,t)     = show t
     posFromTok (pos,t)  = pos
     testTok (pos,t)     = if x == t then Just t else Nothing

在每个输入中,输入都是位置和令牌的元组。您试图将这样的元组当作令牌来对待。对我来说,这个错误为什么会导致您得到特定的错误并不很明显,但是我认为您仍然可以看到这是一个错误。

,

错误消息提示

(Use FlexibleContexts to permit this)

因此,我们可以添加

{-# LANGUAGE FlexibleContexts #-}

位于文件顶部。之后,它可以正常编译。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。