Kotlin Parsec

SunnyTech 2018


Computer scientist Freelance

Lambdada is a french community
of software developers
#FP #Haskell #Idris and more

Kotlin Parsec


Strong Typed Object-Oriented and
Functional programming language

Multiplatform Kotlin

  • Kotlin/JVM for Desktop, Server and Android
  • Kotlin/JS for WebSites
  • Kotlin/Native for iOS, Linux, WebAssembly ...

Kotlin Features

  • Concise e.g. constructors, methods etc.
  • Safer when dealing with null
  • Strong type checker
  • Closure support
  • Class extension

Kotlin Parsec

Expressions EBNF

                 Expr  ::= SExp [('+' | '*') Expr]
                 SExpr ::= NUMBER | ('(' Expr ')')

Expressions & Parser Combinators

    fun Expr()  = SExp() then opt(charIn('+','*') then Expr())
    fun SExpr() = NUMBER or (char('(') then Expr() char(')')
TDD and TDD compliant


Function accepting characters as input
and returning a structure as output

Live Code


CharReader → Response<A>

Live Code

Core Parsers

  • returns succeeds without consuming any input
  • fails fails without consuming any input
  • any succeeds consuming one Character

Parser Combinator

Accept parsers as input and
returning a new parser as output

Live Code

Core Parser Combinators

  • lazy for (mutual) recursive parsers
  • doTry try a parse or consume nothing
  • lookahead try a parser and consume nothing

Monadic Parser Combinators

          map     : Parser<A> → (A → B) → Parser<B> 
          join    : Parser<Parser<A>> → Parser<A> 
          flatMap : Parser<A> → (A → Parser<B>) → Parser<B> 
Live Code

Episode I

The Object-Oriented Menace

Live Code

Episode II

Attack of the Closure

Episode III

Revenge of the Type

Live Code

Flow Parser Combinators

then , or , opt , optrep , rep

Live Code

tail recursion in Kotlin

Allows some algorithms using recursive function
without the risk of stack overflow.

Live Code

Character Parser Combinators

char , charIn , not

Some Examples

  • Expressions aka "Hello world" for parsers :)
  • JSON parser

Conclusion about Parser Combinators

  • Expressive Parser DSL
  • Intensive Functional Composition
  • Efficiency? Not really e.g. JSON ≈ 500k/s
  • Free-Monads?

Conclusion about Kotlin

  • Object-Oriented with(out) Functional paradigm
  • Function type as Class
  • Class Extension
  • Tail recursion support

Thank you!