Skip to content

Commit e8aa275

Browse files
committed
Add a usage example to the README
1 parent 1913ed2 commit e8aa275

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

README.md

+57
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,60 @@
11
# parsing
22

33
A [parser combinator](https://en.wikipedia.org/wiki/Parser_combinator) library.
4+
5+
## Usage Example
6+
7+
A simple calculator for addition and subtraction of natural numbers:
8+
```ts
9+
import either from '@matt.kantor/either'
10+
import {
11+
lazy,
12+
literal,
13+
map,
14+
oneOf,
15+
oneOrMore,
16+
sequence,
17+
type Parser,
18+
} from '@matt.kantor/parsing'
19+
20+
const operator = oneOf([literal('+'), literal('-')])
21+
22+
const number = map(
23+
oneOrMore(
24+
oneOf([
25+
literal('0'),
26+
literal('1'),
27+
literal('2'),
28+
literal('3'),
29+
literal('4'),
30+
literal('5'),
31+
literal('6'),
32+
literal('7'),
33+
literal('8'),
34+
literal('9'),
35+
]),
36+
),
37+
Number,
38+
)
39+
40+
const compoundExpression = map(
41+
sequence([number, operator, lazy(() => expression)]),
42+
([a, operator, b]) => {
43+
switch (operator) {
44+
case '+': return a + b
45+
case '-': return a - b
46+
}
47+
},
48+
)
49+
50+
const expression: Parser<number> = oneOf([compoundExpression, number])
51+
52+
const evaluate = (input: string) =>
53+
either.flatMap(expression(input), ({ remainingInput, output }) =>
54+
remainingInput.length !== 0
55+
? either.makeLeft('excess content followed valid input')
56+
: either.makeRight(output),
57+
)
58+
59+
console.log(evaluate('2+2-1').value) // logs "3"
60+
```

0 commit comments

Comments
 (0)