scala - 如何实现单子(monad)解析?

标签 scala parsing monads

我一直在理解 Monad 的工作原理。我正在使用 Grammar S->aSb 编写解析器。输入是“a^n b^n for n>=0”,例如“aabb”;此解析器的返回值是一个 bool 值。

以前通过为这个语法使用临时变量。现在我想通过使用 Monad 而不是临时变量来实现这个解析器。但我尝试了很多次,但仍然停留在这个问题上。


object Parser {
  case class Parser[+A](parse: List[Char] => Option[(A, List[Char])]) {
    def accepts(l: List[Char]): Boolean
    // If List[Char] is empty after parsing it was successful
    = parse(l).map(_._2.isEmpty).getOrElse(false)

    // Not sure that this exactly does
    def flatMap[B](f: A => Parser[B]): Parser[B] = Parser {
      input => parse(input).flatMap { case (x, midput) => f(x).parse(midput) }
    }

    // a.map( i => i + 1) parses using Parser a and applies function i+1
    def map[B](f: A => B): Parser[B] = Parser {
      input => parse(input) match {
        case Some((t, remains)) => Some((f(t), remains))
        case _ => None
      }
    }

    // a.orElse(b) tries to use Parser a first
    // If a returns None it tries Parser b
    // If b also returns None all rules are exhausted
    def orElse[B](that: Parser[B]): Parser[Either[A, B]] = Parser {
      input => parse(input) match {
        case Some((p, remains)) => Some((Left(p), remains))
        case None => that.parse(input) match {
          case Some((p, remains)) => Some((Right(p), remains))
          case None => None
        }
      }
    }
  }

  // Not sure if this is correct
  def unit[T](x: T): Parser[T] = Parser {
    _ => Some((x, List()))
  }

  // Consumes c if possible
  def char(c: Char): Parser[Unit] = Parser {
    case x :: rest if c == x => Some(((), rest))
    case _ => None
  }

  def main(args: Array[String]): Unit = {
    val S: Parser[Int]
    = char('a').flatMap { _ =>
      S.flatMap { i =>
        char('b').map { _ =>
          i + 1
        }
      }
    }.orElse(unit(0)).map(_.merge)

    S.accepts("".toList) // true
    S.accepts("aaabbb".toList) // true
    S.accepts("aaa".toList) // false
    S.accepts("bbbaaa".toList) // false
  }
}

最佳答案

通常,当我们说“单子(monad)解析”时,我们的意思是使 Parser 成为一个单子(monad)。我们写

class Parser[+A] { ... }

A Parser[A] 获取输入并返回解析后的 A,或者它可能失败,或者可能会留下一些输入。让我们保持简单:Parser[A] 接受一个 List[Char]Option 返回一个 A 和剩余的 List[Char]

case class Parser[+A](parse: List[Char] => Option[(A, List[Char])]) {
  def accepts(l: List[Char]): Boolean
    = parse(l).map(_._2.isEmpty).getOrElse(false)
  // do not bother with the List('#') stuff
}

您使用组合器构建了一个解析器a.flatMap(b) 是一个匹配 a 后跟 b

的解析器
// case class Parser[+A](...) {
  def flatMap[B](f: A => Parser[B]): Parser[B] = Parser { input =>
    parse(input).flatMap { case (x, midput) => f(x).parse(midput) }
  }
// }

Parser.unit(x) 返回 x 而不消耗任何输入,这就是 Monad 很重要的原因。您还应该有 map,它可以在不改变匹配内容的情况下改变返回值。您还需要一个组合器来进行交替。我会把这些留给你去实现。

object Parser {
    def unit[T](x: T): Parser[T] = ???
}
// case class Parser[+A](...) {
    def map[B](f: A => B): Parser[B] = ???

    // left-biased greedy: if this parser succeeds (produces Some) then
    // that parser is never tried (i.e. no backtracking)
    // replacing Option with Seq is the easiest way to get backtracking
    // but we don't need it to define S
    def orElse[B](that: Parser[B]): Parser[Either[A, B]] = ???
// }

您还需要一些基本的 Parser 来构建更复杂的。 Parser.char(x) 匹配单个字符 x 并且不返回任何有用信息。

// object Parser {
  def char(c: Char): Parser[Unit] = Parser {
    case x :: rest if c == x => Some(((), rest))
    case _ => None
  }
// }

然后您可以以一种非常自然的方式定义S。您甚至可以让解析器返回一个 Int,表示匹配了多少 a/多少 b:

lazy val S: Parser[Int]
  = (for { _ <- Parser.char('a')
           i <- S
           _ <- Parser.char('b')
         } yield (i + 1)).orElse(Parser.unit(0)).map(_.merge)
// i.e
lazy val S: Parser[Int]
  = Parser.char('a').flatMap { _ =>
      S.flatMap { i =>
        Parser.char('b').map { _ =>
          i + 1
        }
      }
    }.orElse(Parser.unit(0)).map(_.merge)

S.accepts("".toList) // true
S.accepts("aaabbb".toList) // true
S.accepts("aaa".toList) // false
S.accepts("bbbaaa".toList) // false

您不必在 S 的定义中移动 List[Char],因为我们编写的组合器会为您完成这项工作,只留下语法本身的逻辑。

关于scala - 如何实现单子(monad)解析?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56518179/

相关文章:

scala - 如何使用scala规范化或标准化spark中具有多个列/变量的数据?

java - 我如何可视化查找列表最大数量的递归实现?

java - 使用 tika 解析器的 XPath 应用程序

c++ - 如何在 C++ 中使用 std::optional

Haskell sequencelistIO [a -> IO a] -> a -> IO a

scala - 从 Scala 中的双数组列表创建 Breeze DenseMatrix

scala - 动态创建案例类

c++ - 为什么编译器只向后查找类型和函数声明?

python - 我正在使用电话号码模块来验证电话号码。它运行良好,但我只需要国家号码作为输出

java - 在Springboot应用程序中使用monad来捕获异常