The document describes parser combinators in Scala. Parser combinators allow building parsers from simple parsing functions combined using operators like ~ (sequence) and | (choice). This approach implements recursive descent parsing with backtracking. Examples show building parsers for arithmetic expressions and lambda calculus terms using parser combinators. The key advantages of the parser combinator approach are that it is functional in nature, parsers can be composed from small reusable pieces, and backtracking allows robust handling of parsing errors.
Introduction to Lisp. A survey of lisp's history, current incarnations and advanced features such as list comprehensions, macros and domain-specific-language [DSL] support.
Introduction to Lisp. A survey of lisp's history, current incarnations and advanced features such as list comprehensions, macros and domain-specific-language [DSL] support.
I gave this presentation on January 14, 2010 to the Atlanta Scala user group. It covers Scala's implementation of operator overloading, as well as touching on implicit conversions.
Object Equality In Scala, means comparing two objects by their values and references.Generally, equality is ubiquitous in programming. It is also more tricky than it looks at first glance. This presentation looks at object equality in detail and gives some recommendations to consider when we design our own equality tests.
LISP Language, LISP Introduction, List Processing, LISP Syntax, Lisp Comparison Structures, Lisp Applications. Using of LISP language in Artificial Intelligence
Invented by John McCarthy (1958)
Two simple data structure (atoms and lists)
Heavy use of recursion
Interpretive language
Variations
Scheme
Common Lisp (de facto industrial standard)
Most widely used AI programming language
Functional Programming Paradigm
Low maintenance overhead
When embracing Java 8 we walk down the yellow brick road to the wizard of lambdas. That road usually starts from the fear and terror of learning their syntax until finally getting to understand them and opening our minds to the fruitful fields of functional programming. But this road eventually reaches a final stage: the lambda abuse.
To master the lambdas art means to know when to use them and when not to not damage your brain and, most importantly, other Java developers’. Keep your code readable and maintainable, avoid becoming a lambda addict!
An overview of the programming techniques available and some of the ongoing research in the Haskell community around concurrent and parallel programming.
Practical Functional Programming Presentation by Bogdan Hodorog3Pillar Global
Bogdan Hodorog's presentation on Practical Functional Programming at the Functional Angle Meetup help at 3Pillar's office in Timisoara. Bogdan Hodorog is a Software Engineer who is passionate about building, trying, and playing with software...of all sorts. He currently specializes in Python but is interested in programming languages ad operating systems of all kinds.
The emergence of support of functions and lambda expressions as first-class citizens in Java 8 gives us a tremendous opportunity to adapt the concepts of functional programming to the Java language.
Ruby plays to many programming paradigms. It's an object-oriented language that can be used in a functional or an imperative/procedural way. But Ruby does not often get used as a logic programming language. In this talk I'll explore logic programming using Ruby. What is it, and is it a tool you want to add to your toolbox? We'll touch on several libraries, we'll primary look at an implementation of minikanren (http://minikanren.org/) for Ruby.
LISP, an acronym for list processing, is a programming language that was designed for easy manipulation of data strings. It is a commonly used language for artificial intelligence (AI) programming.
I gave this presentation on January 14, 2010 to the Atlanta Scala user group. It covers Scala's implementation of operator overloading, as well as touching on implicit conversions.
Object Equality In Scala, means comparing two objects by their values and references.Generally, equality is ubiquitous in programming. It is also more tricky than it looks at first glance. This presentation looks at object equality in detail and gives some recommendations to consider when we design our own equality tests.
LISP Language, LISP Introduction, List Processing, LISP Syntax, Lisp Comparison Structures, Lisp Applications. Using of LISP language in Artificial Intelligence
Invented by John McCarthy (1958)
Two simple data structure (atoms and lists)
Heavy use of recursion
Interpretive language
Variations
Scheme
Common Lisp (de facto industrial standard)
Most widely used AI programming language
Functional Programming Paradigm
Low maintenance overhead
When embracing Java 8 we walk down the yellow brick road to the wizard of lambdas. That road usually starts from the fear and terror of learning their syntax until finally getting to understand them and opening our minds to the fruitful fields of functional programming. But this road eventually reaches a final stage: the lambda abuse.
To master the lambdas art means to know when to use them and when not to not damage your brain and, most importantly, other Java developers’. Keep your code readable and maintainable, avoid becoming a lambda addict!
An overview of the programming techniques available and some of the ongoing research in the Haskell community around concurrent and parallel programming.
Practical Functional Programming Presentation by Bogdan Hodorog3Pillar Global
Bogdan Hodorog's presentation on Practical Functional Programming at the Functional Angle Meetup help at 3Pillar's office in Timisoara. Bogdan Hodorog is a Software Engineer who is passionate about building, trying, and playing with software...of all sorts. He currently specializes in Python but is interested in programming languages ad operating systems of all kinds.
The emergence of support of functions and lambda expressions as first-class citizens in Java 8 gives us a tremendous opportunity to adapt the concepts of functional programming to the Java language.
Ruby plays to many programming paradigms. It's an object-oriented language that can be used in a functional or an imperative/procedural way. But Ruby does not often get used as a logic programming language. In this talk I'll explore logic programming using Ruby. What is it, and is it a tool you want to add to your toolbox? We'll touch on several libraries, we'll primary look at an implementation of minikanren (http://minikanren.org/) for Ruby.
LISP, an acronym for list processing, is a programming language that was designed for easy manipulation of data strings. It is a commonly used language for artificial intelligence (AI) programming.
Algorithm and Programming (Introduction of dev pascal, data type, value, and ...Adam Mukharil Bachtiar
This file contains explanation about introduction of dev pascal, data type, value, and identifier. This file was used in my Algorithm and Programming Class.
PetitParser is a dynamic parser framework combining ideas from scannerless parsing, parser combinators, parsing expression grammars and packrat parsers. In this hands-on session we learn how to build simple parsers and how to model, test, compose and reuse complex grammars. Additionally, we will look at some tools and the reflective facilities provided by the PetitParser framework. Basic knowledge of the Smalltalk programming language is a requirement. Bring your laptop to reproduce the examples and solve some simple tasks.
TMPA-2017: Functional Parser of Markdown Language Based on Monad Combining an...Iosif Itkin
TMPA-2017: Tools and Methods of Program Analysis
3-4 March, 2017, Hotel Holiday Inn Moscow Vinogradovo, Moscow
Functional Parser of Markdown Language Based on Monad Combining and Monoidal Source Stream Representation
Georgy Lukyanov, Artem Pelenitsyn, Southern Federal University
For video follow the link: https://youtu.be/fDGG46gnOi0
Would like to know more?
Visit our website:
www.tmpaconf.org
www.exactprosystems.com/events/tmpa
Follow us:
https://www.linkedin.com/company/exactpro-systems-llc?trk=biz-companies-cym
https://twitter.com/exactpro
Use PEG to Write a Programming Language ParserYodalee
PEG is a replacement to CFG. It is more powerful and can be more precise. In this slide I give a short introduction to PEG, the concept behind a programming language. Finally I write a parser for our programming language simple.
This lecture is about The R Language use for statistical computing for beginners who want to start working on financial analytics using R software. Moreover, lecture is beneficial for finance professional who want to work on R for financial data analysis.
this presentation is an introduction to R programming language.we will talk about usage, history, data structure and feathers of R programming language.
Shows some advanced REXX techniques to make your programs more efficient and more readable for easier debugging. Also describes some tips for creating file and program structures not discussed in a typical REXX class.
Similar to Parsers Combinators in Scala, Ilya @lambdamix Kliuchnikov (20)
UiPath Test Automation using UiPath Test Suite series, part 6DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 6. In this session, we will cover Test Automation with generative AI and Open AI.
UiPath Test Automation with generative AI and Open AI webinar offers an in-depth exploration of leveraging cutting-edge technologies for test automation within the UiPath platform. Attendees will delve into the integration of generative AI, a test automation solution, with Open AI advanced natural language processing capabilities.
Throughout the session, participants will discover how this synergy empowers testers to automate repetitive tasks, enhance testing accuracy, and expedite the software testing life cycle. Topics covered include the seamless integration process, practical use cases, and the benefits of harnessing AI-driven automation for UiPath testing initiatives. By attending this webinar, testers, and automation professionals can gain valuable insights into harnessing the power of AI to optimize their test automation workflows within the UiPath ecosystem, ultimately driving efficiency and quality in software development processes.
What will you get from this session?
1. Insights into integrating generative AI.
2. Understanding how this integration enhances test automation within the UiPath platform
3. Practical demonstrations
4. Exploration of real-world use cases illustrating the benefits of AI-driven test automation for UiPath
Topics covered:
What is generative AI
Test Automation with generative AI and Open AI.
UiPath integration with generative AI
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
Dr. Sean Tan, Head of Data Science, Changi Airport Group
Discover how Changi Airport Group (CAG) leverages graph technologies and generative AI to revolutionize their search capabilities. This session delves into the unique search needs of CAG’s diverse passengers and customers, showcasing how graph data structures enhance the accuracy and relevance of AI-generated search results, mitigating the risk of “hallucinations” and improving the overall customer journey.
In the rapidly evolving landscape of technologies, XML continues to play a vital role in structuring, storing, and transporting data across diverse systems. The recent advancements in artificial intelligence (AI) present new methodologies for enhancing XML development workflows, introducing efficiency, automation, and intelligent capabilities. This presentation will outline the scope and perspective of utilizing AI in XML development. The potential benefits and the possible pitfalls will be highlighted, providing a balanced view of the subject.
We will explore the capabilities of AI in understanding XML markup languages and autonomously creating structured XML content. Additionally, we will examine the capacity of AI to enrich plain text with appropriate XML markup. Practical examples and methodological guidelines will be provided to elucidate how AI can be effectively prompted to interpret and generate accurate XML markup.
Further emphasis will be placed on the role of AI in developing XSLT, or schemas such as XSD and Schematron. We will address the techniques and strategies adopted to create prompts for generating code, explaining code, or refactoring the code, and the results achieved.
The discussion will extend to how AI can be used to transform XML content. In particular, the focus will be on the use of AI XPath extension functions in XSLT, Schematron, Schematron Quick Fixes, or for XML content refactoring.
The presentation aims to deliver a comprehensive overview of AI usage in XML development, providing attendees with the necessary knowledge to make informed decisions. Whether you’re at the early stages of adopting AI or considering integrating it in advanced XML development, this presentation will cover all levels of expertise.
By highlighting the potential advantages and challenges of integrating AI with XML development tools and languages, the presentation seeks to inspire thoughtful conversation around the future of XML development. We’ll not only delve into the technical aspects of AI-powered XML development but also discuss practical implications and possible future directions.
Building RAG with self-deployed Milvus vector database and Snowpark Container...Zilliz
This talk will give hands-on advice on building RAG applications with an open-source Milvus database deployed as a docker container. We will also introduce the integration of Milvus with Snowpark Container Services.
In his public lecture, Christian Timmerer provides insights into the fascinating history of video streaming, starting from its humble beginnings before YouTube to the groundbreaking technologies that now dominate platforms like Netflix and ORF ON. Timmerer also presents provocative contributions of his own that have significantly influenced the industry. He concludes by looking at future challenges and invites the audience to join in a discussion.
UiPath Test Automation using UiPath Test Suite series, part 5DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 5. In this session, we will cover CI/CD with devops.
Topics covered:
CI/CD with in UiPath
End-to-end overview of CI/CD pipeline with Azure devops
Speaker:
Lyndsey Byblow, Test Suite Sales Engineer @ UiPath, Inc.
Threats to mobile devices are more prevalent and increasing in scope and complexity. Users of mobile devices desire to take full advantage of the features
available on those devices, but many of the features provide convenience and capability but sacrifice security. This best practices guide outlines steps the users can take to better protect personal devices and information.
Epistemic Interaction - tuning interfaces to provide information for AI supportAlan Dix
Paper presented at SYNERGY workshop at AVI 2024, Genoa, Italy. 3rd June 2024
https://alandix.com/academic/papers/synergy2024-epistemic/
As machine learning integrates deeper into human-computer interactions, the concept of epistemic interaction emerges, aiming to refine these interactions to enhance system adaptability. This approach encourages minor, intentional adjustments in user behaviour to enrich the data available for system learning. This paper introduces epistemic interaction within the context of human-system communication, illustrating how deliberate interaction design can improve system understanding and adaptation. Through concrete examples, we demonstrate the potential of epistemic interaction to significantly advance human-computer interaction by leveraging intuitive human communication strategies to inform system design and functionality, offering a novel pathway for enriching user-system engagements.
Maruthi Prithivirajan, Head of ASEAN & IN Solution Architecture, Neo4j
Get an inside look at the latest Neo4j innovations that enable relationship-driven intelligence at scale. Learn more about the newest cloud integrations and product enhancements that make Neo4j an essential choice for developers building apps with interconnected data and generative AI.
Removing Uninteresting Bytes in Software FuzzingAftab Hussain
Imagine a world where software fuzzing, the process of mutating bytes in test seeds to uncover hidden and erroneous program behaviors, becomes faster and more effective. A lot depends on the initial seeds, which can significantly dictate the trajectory of a fuzzing campaign, particularly in terms of how long it takes to uncover interesting behaviour in your code. We introduce DIAR, a technique designed to speedup fuzzing campaigns by pinpointing and eliminating those uninteresting bytes in the seeds. Picture this: instead of wasting valuable resources on meaningless mutations in large, bloated seeds, DIAR removes the unnecessary bytes, streamlining the entire process.
In this work, we equipped AFL, a popular fuzzer, with DIAR and examined two critical Linux libraries -- Libxml's xmllint, a tool for parsing xml documents, and Binutil's readelf, an essential debugging and security analysis command-line tool used to display detailed information about ELF (Executable and Linkable Format). Our preliminary results show that AFL+DIAR does not only discover new paths more quickly but also achieves higher coverage overall. This work thus showcases how starting with lean and optimized seeds can lead to faster, more comprehensive fuzzing campaigns -- and DIAR helps you find such seeds.
- These are slides of the talk given at IEEE International Conference on Software Testing Verification and Validation Workshop, ICSTW 2022.
GraphSummit Singapore | The Future of Agility: Supercharging Digital Transfor...Neo4j
Leonard Jayamohan, Partner & Generative AI Lead, Deloitte
This keynote will reveal how Deloitte leverages Neo4j’s graph power for groundbreaking digital twin solutions, achieving a staggering 100x performance boost. Discover the essential role knowledge graphs play in successful generative AI implementations. Plus, get an exclusive look at an innovative Neo4j + Generative AI solution Deloitte is developing in-house.
How to Get CNIC Information System with Paksim Ga.pptxdanishmna97
Pakdata Cf is a groundbreaking system designed to streamline and facilitate access to CNIC information. This innovative platform leverages advanced technology to provide users with efficient and secure access to their CNIC details.
Communications Mining Series - Zero to Hero - Session 1DianaGray10
This session provides introduction to UiPath Communication Mining, importance and platform overview. You will acquire a good understand of the phases in Communication Mining as we go over the platform with you. Topics covered:
• Communication Mining Overview
• Why is it important?
• How can it help today’s business and the benefits
• Phases in Communication Mining
• Demo on Platform overview
• Q/A
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofsAlex Pruden
This paper presents Reef, a system for generating publicly verifiable succinct non-interactive zero-knowledge proofs that a committed document matches or does not match a regular expression. We describe applications such as proving the strength of passwords, the provenance of email despite redactions, the validity of oblivious DNS queries, and the existence of mutations in DNA. Reef supports the Perl Compatible Regular Expression syntax, including wildcards, alternation, ranges, capture groups, Kleene star, negations, and lookarounds. Reef introduces a new type of automata, Skipping Alternating Finite Automata (SAFA), that skips irrelevant parts of a document when producing proofs without undermining soundness, and instantiates SAFA with a lookup argument. Our experimental evaluation confirms that Reef can generate proofs for documents with 32M characters; the proofs are small and cheap to verify (under a second).
Paper: https://eprint.iacr.org/2023/1886
4. Intro: combinators, parsers
Scala Parser Combinators from the Ground Up
How to write typical parser
33/35 11/14 Pros, cons 8/9 4/13
Advanced techniques
4
5. Parser?
● Трансформирует текст в структуру
+
2*3 + 4 * 3
2 3
5
6. Hello, parser
import scala.util.parsing.combinator._
import syntactical.StandardTokenParsers
sealed trait Expr
case class Num(i: Int) extends Expr
case class Var(n: String) extends Expr
case class Plus(e1: Expr, e2: Expr) extends Expr
case class Mult(e1: Expr, e2: Expr) extends Expr
object ArithParsers extends StandardTokenParsers with ImplicitConversions {
lexical.delimiters += ("(", ")", "+", "*")
def expr: Parser[Expr] =
term ~ ("+" ~> expr) ^^ Plus | term
def term: Parser[Expr] =
factor ~ ("*" ~> term) ^^ Mult | factor
def factor: Parser[Expr] =
numericLit ^^ { s => Num(s.toInt) } | ident ^^ Var | "(" ~> expr <~ ")"
def parseExpr(s: String) = phrase(expr)(new lexical.Scanner(s))
}
scala> ArithParsers.parseExpr("1")
res1: ArithParsers.ParseResult[parsers2.Expr] = [1.2] parsed: Num(1)
scala> ArithParsers.parseExpr("1 + 1 * 2")
res2: ArithParsers.ParseResult[parsers2.Expr] = [1.10] parsed: Plus(Num(1),Mult(Num(1),Num(2)))
scala> ArithParsers.parseExpr("a * (a * a)")
res3: ArithParsers.ParseResult[parsers2.Expr] = [1.12] parsed: Mult(Var(a),Mult(Var(a),Var(a)))
6
7. Example 2: Lambda calculus
t ::= terms:
x variable
λx.t abstraction
tt application
x y z = ((x y) z)
λx.λy.y = λx.(λy.y)
7
8. Example 2
sealed trait Term
case class Var(n: String) extends Term
case class Lam(v: Var, body: Term) extends Term
case class App(t1: Term, t2: Term) extends Term
object LamParsers extends StandardTokenParsers with ImplicitConversions with PackratParsers {
lexical.delimiters += ("(", ")", ".", "")
lazy val term: PackratParser[Term] =
appTerm | lam
lazy val vrb: PackratParser[Var] =
ident ^^ Var
lazy val lam: PackratParser[Term] =
("" ~> vrb) ~ ("." ~> term) ^^ Lam
lazy val appTerm: PackratParser[Term] =
appTerm ~ aTerm ^^ App | aTerm
lazy val aTerm: PackratParser[Term] =
vrb | "(" ~> term <~ ")"
def parseTerm(s: String) =
phrase(term)(new lexical.Scanner(s))
}
scala> LamParsers.parseTerm("x y z")
res1: LamParsers.ParseResult[parsers.Term] = [1.6] parsed: App(App(Var(x),Var(y)),Var(z))
scala> LamParsers.parseTerm("""x.y.x y""")
res2: LamParsers.ParseResult[parsers.Term] = [1.10] parsed:
Lam(Var(x),Lam(Var(y),App(Var(x),Var(y))))
scala> LamParsers.parseTerm("""(x.x x) (x. x x)""")
res3: LamParsers.ParseResult[parsers.Term] = [1.19] parsed:
App(Lam(Var(x),App(Var(x),Var(x))),Lam(Var(x),App(Var(x),Var(x)))) 8
11. Принципы комбинаторных библиотек
● Соответствие терминологии библиотеки и
терминологии предметной области.
● Состав
● типы,
● примитивы,
● комбинаторы первого порядка,
● комбинаторы высшего порядка.
● Свойство замыкания (композиционность).
● Возможность эффективной реализации.
E. Кирпичев. Элементы функциональных языков. Практика функционального 11
программирования №3.
16. Parsers in Scala
C9 Lectures: Dr. Erik Meijer - Functional Programming Fundamentals Chapter 8 of 13
A. Moors, F. Piessens, M. Odersky. Parser Combinators in Scala. Report CW 49 // Feb 2008
16
18. Parsers in Scala are functional
Background:
● W. Burge. Recursive Programming Techniques.
Addison-Wesley, 1975.
● Ph. Wadler. How to Replace Failure by a List of
Successes. A method for exception handling,
backtracking, and pattern matching in lazy
functional languages // 1985
● G. Hutton. Higher-order functions for parsing //
Journal of functional programming. 1992/2
● J. Fokker. Functional Parsers // 1995
18
19. Parser?
● Трансформирует текст в структуру
+
2*3 + 4 * 3
2 3
19
20. Парсер – это функция
type Parser[A] = String => A
Нет композиции функций, не обязательно парсить всю строку
type Parser[A] = String => (A, String)
Может закончиться неудачей
type Parser[A] = String => Option[(A, String)]
20
28. Where is a problem?
trait SimpleParsers extends SimpleResults {
trait Parser[+T] extends (Input => Result[T]) {
def apply(in: Input): Result[T]
def |[U >: T](p: => Parser[U]): Parser[U] = new Parser[U] {
def apply(in: Input) = Parser.this(in) match {
case Failure(_, _) => p(in)
case Success(x, n) => Success(x, n)}}
def ~[U](p: => Parser[U]): Parser[(T, U)] = new Parser[(T, U)] {
def apply(in: Input) = Parser.this(in) match {
case Success(x, next) => p(next) match {
case Success(x2, next2) => Success((x, x2), next2)
case Failure(m, n) => Failure(m, n) }
case Failure(m, n) => Failure(m, n)}}
}
}
object OXOParser extends StringParsers {
def oxo = accept('o') ~ accept('x') ~ accept('o')
def oxos: Parser[Any] =
(oxo ~ accept(' ') ~ oxos | oxo)
}
28
29. Too much “threading”
trait SimpleParsers extends SimpleResults {
trait Parser[+T] extends (Input => Result[T]) {
def apply(in: Input): Result[T]
def |[U >: T](p: => Parser[U]): Parser[U] = new Parser[U] {
def apply(in: Input) = Parser.this(in) match {
case Failure(_, _) => p(in)
case Success(x, n) => Success(x, n)}}
def ~[U](p: => Parser[U]): Parser[(T, U)] = new Parser[(T, U)] {
def apply(in: Input) = Parser.this(in) match {
case Success(x, next) => p(next) match {
case Success(x2, next2) => Success((x, x2), next2)
case Failure(m, n) => Failure(m, n) }
case Failure(m, n) => Failure(m, n)}}
}
}
object OXOParser extends StringParsers {
def oxo = accept('o') ~ accept('x') ~ accept('o')
def oxos: Parser[Any] =
(oxo ~ accept(' ') ~ oxos | oxo)
}
29
30. Improved Results
trait SimpleResults {
type Input
trait Result[+T] {
def next: Input
def map[U](f: T => U): Result[U]
def flatMapWithNext[U](f: T => Input => Result[U]): Result[U]
def append[U >: T](alt: => Result[U]): Result[U]
}
case class Success[+T](result: T, next: Input) extends Result[T] {
def map[U](f: T => U) = Success(f(result), next)
def flatMapWithNext[U](f: T => Input => Result[U]) = f(result)(next)
def append[U >: T](alt: => Result[U]) = this
}
case class Failure(msg: String, next: Input) extends Result[Nothing] {
def map[U](f: Nothing => U) = this
def flatMapWithNext[U](f: Nothing => Input => Result[U]) = this
def append[U](alt: => Result[U]) = alt
}
}
●map -...
●flatMapWithNext - ...
●append – for multiple results (we do not consider it here)
30
31. Parser is a function with many results
type Parser[A] = String => A
type Parser[A] = String => (A, String)
type Parser[A] = String => Option[(A, String)]
type Parser[A] = String => List[(A, String)]
31
32. After improving
trait SimpleResults {
type Input
trait Result[+T] {
def next: Input
def map[U](f: T => U): Result[U]
def flatMapWithNext[U](f: T => Input => Result[U]): Result[U]
def append[U >: T](alt: => Result[U]): Result[U]
}
case class Success[+T](result: T, next: Input) extends Result[T] {
def map[U](f: T => U) = Success(f(result), next)
def flatMapWithNext[U](f: T => Input => Result[U]) = f(result)(next)
def append[U >: T](alt: => Result[U]) = this
}
case class Failure(msg: String, next: Input) extends Result[Nothing] {
def map[U](f: Nothing => U) = this
def flatMapWithNext[U](f: Nothing => Input => Result[U]) = this
def append[U](alt: => Result[U]) = alt
}
}
trait SimpleParsers extends SimpleResults {
abstract class Parser[+T] extends (Input => Result[T]) {
def apply(in: Input): Result[T]
def flatMap[U](f: T => Parser[U]): Parser[U] = new Parser[U] {
def apply(in: Input) = Parser.this(in) flatMapWithNext (f)
}
def map[U](f: T => U): Parser[U] = new Parser[U] {
def apply(in: Input) = Parser.this(in) map (f)
}
def |[U >: T](p: => Parser[U]): Parser[U] = new Parser[U] {
def apply(in: Input) = Parser.this(in) append p(in)
}
def ~[U](p: => Parser[U]): Parser[(T, U)] =
for (a <- this; b <- p) yield (a, b)
Hey! 32
}
}
37. Real Parsers
package scala.util.parsing.combinator
trait Parsers { Stream annotated with
type Elem
type Input = Reader[Elem] coordinates
sealed abstract class ParseResult[+T]
case class Success[+T](result: T, override val next: Input) extends ParseResult[T]
sealed abstract class NoSuccess(val msg: String, override val next: Input)
extends ParseResult[Nothing]
case class Failure(override val msg: String, override val next: Input)
extends NoSuccess(msg, next)
case class Error(override val msg: String, override val next: Input)
extends NoSuccess(msg, next)
...
abstract class Parser[+T] extends (Input => ParseResult[T]) { Controlling
... backtracking
}
case class ~[+a, +b](_1: a, _2: b) {
override def toString = "("+ _1 +"~"+ _2 +")"
}
Deconstructing sequencing
}
package scala.util.parsing.input
abstract class Reader[+T] {
def first: T
def rest: Reader[T] 37
}
53. PROS
● Toт же язык (Scala) – не нужно учить новый
инструмент.
● Исполняемая грамматика - всегда
актуальный код.
● Краткость + богатая выразительность: LL(*) и
больше (в том числе, контекстные
грамматики).
● Можно делать fusion синтаксического
разбора и чего-нибудь еще.
● Модульность 53
54. CONS
● Некоторые простые вещи могут
кодироваться очень непросто.
● Performance.
54
59. + Left Recursion
sealed trait Term
case class Var(n: String) extends Term
case class Lam(v: Var, body: Term) extends Term
case class App(t1: Term, t2: Term) extends Term
object LamParsers extends StandardTokenParsers with ImplicitConversions with PackratParsers {
lexical.delimiters += ("(", ")", ".", "")
lazy val term: PackratParser[Term] =
appTerm | lam
lazy val vrb: PackratParser[Var] =
ident ^^ Var
lazy val lam: PackratParser[Term] =
("" ~> vrb) ~ ("." ~> term) ^^ Lam
lazy val appTerm: PackratParser[Term] =
appTerm ~ aTerm ^^ App | aTerm
lazy val aTerm: PackratParser[Term] =
vrb | "(" ~> term <~ ")"
def parseTerm(s: String) =
phrase(term)(new lexical.Scanner(s))
}
59
60. + Left Recursion
sealed trait Term
case class Var(n: String) extends Term
case class Lam(v: Var, body: Term) extends Term
case class App(t1: Term, t2: Term) extends Term
object LamParsers extends StandardTokenParsers with ImplicitConversions with PackratParsers {
lexical.delimiters += ("(", ")", ".", "")
lazy val term: PackratParser[Term] =
appTerm | lam
lazy val vrb: PackratParser[Var] =
ident ^^ Var
lazy val lam: PackratParser[Term] =
("" ~> vrb) ~ ("." ~> term) ^^ Lam
lazy val appTerm: PackratParser[Term] =
appTerm ~ aTerm ^^ App | aTerm lazy val
lazy val aTerm: PackratParser[Term] =
vrb | "(" ~> term <~ ")"
def parseTerm(s: String) =
phrase(term)(new lexical.Scanner(s))
}
60
61. Without Left Recursion
sealed trait Term
case class Var(n: String) extends Term
case class Lam(v: Var, body: Term) extends Term
case class App(t1: Term, t2: Term) extends Term
object LamParsers extends StandardTokenParsers with ImplicitConversions {
lexical.delimiters += ("(", ")", ".", "")
lazy val term: Parser[Term] =
appTerm | lam
lazy val vrb: Parser[Var] =
ident ^^ Var
lazy val lam: Parser[Term] =
("" ~> vrb) ~ ("." ~> term) ^^ Lam
lazy val appTerm: Parser[Term] =
(aTerm +) ^^ { _.reduceLeft(App) }
lazy val aTerm: Parser[Term] =
vrb | "(" ~> term <~ ")"
def parseTerm(s: String) =
phrase(term)(new lexical.Scanner(s))
}
61