在案例块中解析

swa*_*lay 2 monads parsing haskell functional-programming do-notation

因此,我正在编写自己的解析器,该解析器快要完成了,但是我一直陷入函数返回的困境。我的返回值是case,但是在其中,case我必须进行解析,但无法使其正常工作。

parseCompontntsTile :: Tile -> Parser Tile
parseCompontntsTile (Tile pos fix wiel) = 
    do  parseWhiteSpace
        patern <- match "pos:" `mplus`     match "fixed:" `mplus` match "wheel:"
        return (case patern of
                 "pos"   -> (Tile  parsePosition  fix  wiel)
                 "fixed" -> (Tile  pos     parseFixed  wiel)
                 "wheel" -> (Tile  pos     fix    parseWiel) )
Run Code Online (Sandbox Code Playgroud)

功能parsePosition来自类型parsePosition :: Parser Coord; tile的构造函数为Coord Bool Bool

当然,这是行不通的,因为会parsePosition返回Parser Coord并且期望返回Coord(没有“ parse”)。通常情况下,我只是将其“拆包”,但是,如何在一个包装箱内进行呢?

谢谢你的帮助

chi*_*chi 5

通常情况下,我只是将其“拆包”,但是,如何在一个包装箱内进行呢?

您需要先“推动”最终return进入案例分支

pattern <- match "pos:" `mplus`  ....
case pattern of
   "pos"   -> return (Tile  parsePosition  fix  wiel)
   "fixed" -> return (Tile  pos     parseFixed  wiel)
   "wheel" -> return (Tile  pos     fix    parseWiel)
Run Code Online (Sandbox Code Playgroud)

现在,让分支在解析器monad中运行,您可以照常解压缩:

pattern <- match "pos:" `mplus`  ....
case pattern of
   "pos"   -> do  -- alternative 1
      pp <- parsePosition
      return (Tile pp fix wiel)
   "fixed" -> -- alternative 2
      (\pf -> Tile pos pf wiel) <$> parseFixed
   "wheel" -> ...
Run Code Online (Sandbox Code Playgroud)