From 8ef91f03fac2bad20fb927fe2ca2782c66fdb513 Mon Sep 17 00:00:00 2001 From: Akshay Nair Date: Thu, 6 Jan 2022 23:41:32 +0530 Subject: feat: adds more parser combinators --- src/index.ts | 12 +++++++++++- src/parser.ts | 24 +++++++++++++++++++++++- 2 files changed, 34 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/index.ts b/src/index.ts index d236473..582f9be 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,5 @@ import { constant, flow, identity, pipe } from 'fp-ts/function' -import { mapTo, symbol } from './parser' +import { andThen, delimited, mapTo, optional, pair, symbol } from './parser' export const start = mapTo(symbol('^'), constant({ tag: 'Start' } as Expr)) export const end = mapTo(symbol('$'), constant({ tag: 'End' } as Expr)) @@ -27,6 +27,16 @@ type Expr = | { tag: 'Truthy' } | { tag: 'Falsey' } +export const expressionP = symbol('fuck') + +export const parser = pair( + pair( + optional(start), + expressionP, + ), + optional(end), +) + /* ^ $ => start and end of list diff --git a/src/parser.ts b/src/parser.ts index f8dcd44..5ccba43 100644 --- a/src/parser.ts +++ b/src/parser.ts @@ -1,5 +1,6 @@ import { flow, pipe } from 'fp-ts/function' -import { Either, left, right, map, chain, orElse } from 'fp-ts/Either' +import { Either, left, right, map, chain, orElse, fold } from 'fp-ts/Either' +import { none, some, Option } from 'fp-ts/lib/Option' export type char = string @@ -117,3 +118,24 @@ export const mapTo = (p: Parser, f: (p: I) => R): Parser => p, map(([v, inp]) => [f(v), inp]) ) + +export const andThen = (f: (p: I) => Parser) => (p: Parser): Parser => + flow( + p, + chain(([v, inp]) => f(v)(inp)), + ) + +export const optional = (p: Parser): Parser> => + flow( + p, + fold( + ([_, inp]) => right([none, inp]), + ([v, inp]) => right([some(v), inp]) + ) + ) + +export const pair = (a: Parser, b: Parser): Parser<[A, B]> => pipe( + a, + andThen(ra => mapTo(b, rb => [ra, rb])) +) + -- cgit v1.3.1