簡體   English   中英

如何在 Haskell 中解析布爾表達式

[英]How to parse a bool expression in Haskell

我正在嘗試解析 Haskell 中的布爾表達式。 這一行給了我一個錯誤: BoolExpr <$> parseBoolOp <*> (n : ns) 這是錯誤:

• Couldn't match type ‘[]’ with ‘Parser’
  Expected type: Parser [Expr]
    Actual type: [Expr]
-- define the expression types
data Expr
  = BoolExpr BoolOp [Expr]
  deriving (Show, Eq)

-- define the type for bool value
data Value
  = BoolVal Bool
  deriving (Show, Eq)

-- many x = Parser.some x <|> pure []
-- some x = (:) <$> x <*> Parser.many x
kstar :: Alternative f => f a -> f [a]
kstar x = kplus x <|> pure []
kplus :: Alternative f => f a -> f [a]
kplus x = (:) <$> x <*> kstar x 

symbol :: String -> Parser String 
symbol xs = token (string xs)

-- a bool expression is the operator followed by one or more expressions that we have to parse
-- TODO: add bool expressions
boolExpr :: Parser Expr
boolExpr = do
  n <- parseExpr
  ns <- kstar (symbol "," >> parseExpr)
  BoolExpr <$> parseBoolOp <*> (n : ns)

-- an atom is a literalExpr, which can be an actual literal or some other things
parseAtom :: Parser Expr
parseAtom =
  do
    literalExpr

-- the main parsing function which alternates between all the options you have
parseExpr :: Parser Expr
parseExpr =
  do
    parseAtom
    <|> parseParens boolExpr
    <|> parseParens parseExpr

-- implement parsing bool operations, these are 'and' and 'or'
parseBoolOp :: Parser BoolOp
parseBoolOp =
  do symbol "and" >> return And
    <|> do symbol "or" >> return Or

boolExpr 期待Parser [Expr]但我只返回一個[Expr] 有沒有辦法解決這個問題或以其他方式做到這一點? 當我嘗試純 (n:ns) 時, evalStr "(and true (and false true) true)"返回Left (ParseError "'a' didn't match expected character")而不是Right (BoolVal False)

表達式(n : ns)是一個列表。 因此,編譯器認為應用運算符<*><$>應該在上下文[]中使用,而您需要Parser

我猜你需要pure (n : ns)代替。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM