Skip to content

mkantor/parsing

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

20 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

parsing

A parser combinator library.

Usage Example

A simple calculator for addition and subtraction of natural numbers:

import either from '@matt.kantor/either'
import {
  lazy,
  literal,
  map,
  oneOf,
  oneOrMore,
  sequence,
  type Parser,
} from '@matt.kantor/parsing'

const operator = oneOf([literal('+'), literal('-')])

const number = map(
  oneOrMore(
    oneOf([
      literal('0'),
      literal('1'),
      literal('2'),
      literal('3'),
      literal('4'),
      literal('5'),
      literal('6'),
      literal('7'),
      literal('8'),
      literal('9'),
    ]),
  ),
  Number,
)

const compoundExpression = map(
  sequence([number, operator, lazy(() => expression)]),
  ([a, operator, b]) => {
    switch (operator) {
      case '+': return a + b
      case '-': return a - b
    }
  },
)

const expression: Parser<number> = oneOf([compoundExpression, number])

const evaluate = (input: string) =>
  either.flatMap(expression(input), ({ remainingInput, output }) =>
    remainingInput.length !== 0
      ? either.makeLeft('excess content followed valid input')
      : either.makeRight(output),
  )

console.log(evaluate('2+2-1').value) // logs "3"

About

A parser combinator library.

Resources

License

Stars

Watchers

Forks

Packages

No packages published