I am a beginner user of Haskell and the Megaparsec library. While parsing a line of text, I come to a point where I need to parse the remaining text in the line up until the end-of-line (either LF or CRLF). My thought was to use some
and noneOf
but cannot get the code to compile even after testing in GHCi as follows:
λ> import Data.Text (Text, pack)
λ> import Data.Void
λ> import Text.Megaparsec as M
λ> import Text.Megaparsec.Char as M
λ> import qualified Text.Megaparsec.Char.Lexer as L
λ> type Parser = Parsec Void Text
λ>
λ> parse (some (noneOf "\r\n")) "" (pack "a line of text\r\n")
Right "a line of text"
λ> parse (some (noneOf "\r\n")) "" (pack "a line of text\n")
Right "a line of text"
So the parser (some (noneOf "\r\n"))
compiles successfully and returns what I expected: "a line of text" not including the end-of-line character(s). However, I cannot get the following code to compile in a source file
pLineValue :: Parser Text
pLineValue = do
str <- (some (noneOf "\r\n"))
return (pack str)
The compiler gives following error:
• Ambiguous type variable ‘f0’ arising from a use of ‘noneOf’
prevents the constraint ‘(Foldable f0)’ from being solved.
Probable fix: use a type annotation to specify what ‘f0’ should be.
These potential instances exist:
instance Foldable (Either a) -- Defined in ‘Data.Foldable’
instance Foldable Maybe -- Defined in ‘Data.Foldable’
instance Foldable ((,) a) -- Defined in ‘Data.Foldable’
...plus one other
...plus 37 instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
• In the first argument of ‘some’, namely ‘(noneOf "\r\n")’
In a stmt of a 'do' block: str <- (some (noneOf "\r\n"))
In the expression:
do str <- (some (noneOf "\r\n"))
return (pack str)
|
78 | str <- (some (noneOf "\r\n"))
| ^^^^^^^^^^^^^
What am I doing wrong? What is the correct syntax in the source file? or is there a better approach to parse the remaining text up to but not including the LF or CRLF ending? I'd appreciate any help, Thanks.