From e01cb693bc5737792e2b37abfd98d2d8f81bac4d Mon Sep 17 00:00:00 2001 From: Akshay Nair Date: Thu, 10 Aug 2023 22:45:00 +0530 Subject: feat: adds simple evaluator --- src/utils/adt.ts | 5 +++++ src/utils/parser-comb.ts | 15 ++------------- src/utils/result.ts | 14 ++++++++++++++ 3 files changed, 21 insertions(+), 13 deletions(-) create mode 100644 src/utils/result.ts (limited to 'src/utils') diff --git a/src/utils/adt.ts b/src/utils/adt.ts index e9a6c51..7234f67 100644 --- a/src/utils/adt.ts +++ b/src/utils/adt.ts @@ -5,6 +5,11 @@ export const match = [key in T['tag'] | '_']?: (v: TagValue) => R }): R => ((pattern as any)[tag.tag] || (pattern._ as any))(tag.value) +export const matchString = + (key: T, pattern: { + [key in T | '_']?: (key: key) => R + }): R => ((pattern as any)[key] || (pattern._ as any))(key) + type Tag = { tag: N; value: V } export type Enum = { [N in keyof T]: Tag }[keyof T] diff --git a/src/utils/parser-comb.ts b/src/utils/parser-comb.ts index 49f633e..e0665f6 100644 --- a/src/utils/parser-comb.ts +++ b/src/utils/parser-comb.ts @@ -1,16 +1,5 @@ -import { Enum, constructors, match } from './adt'; - -export type Result = Enum<{ Ok: V, Err: E }> -export const Result = constructors>() - -export const mapResult = (res: Result, fn: (_: A) => B): Result => - chainResult(res, a => Result.Ok(fn(a))) - -export const chainResult = (res: Result, fn: (_: A) => Result): Result => - match(res, { - Ok: a => fn(a), - Err: e => Result.Err(e), - }); +import { match } from './adt'; +import { Result, mapResult, chainResult } from './result'; export type ParseResult = Result<{ value: T, input: string }, { error: string, input: string }>; diff --git a/src/utils/result.ts b/src/utils/result.ts new file mode 100644 index 0000000..c0120b8 --- /dev/null +++ b/src/utils/result.ts @@ -0,0 +1,14 @@ +import { Enum, constructors, match } from "./adt"; + +export type Result = Enum<{ Ok: V, Err: E }> +export const Result = constructors>() + +export const mapResult = (res: Result, fn: (_: A) => B): Result => + chainResult(res, a => Result.Ok(fn(a))) + +export const chainResult = (res: Result, fn: (_: A) => Result): Result => + match(res, { + Ok: a => fn(a), + Err: e => Result.Err(e), + }); + -- cgit v1.3.1