From ac50bb70e668c55392bc2e9210e44e12a9ae0021 Mon Sep 17 00:00:00 2001 From: ivanjermakov Date: Fri, 19 Apr 2024 13:27:42 +0200 Subject: [PATCH] Std: `Future::map`, `Future::flatMap` --- src/semantic/index.ts | 2 ++ src/std/future.no | 24 +++++++++++++++++++++--- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/src/semantic/index.ts b/src/semantic/index.ts index da4746fe..3d969caa 100644 --- a/src/semantic/index.ts +++ b/src/semantic/index.ts @@ -335,6 +335,8 @@ const checkFnDef = (fnDef: FnDef, ctx: Context): void => { } enterScope(module, fnScope, ctx) + // TODO: find await-ops and decide whether fn is awaiting + const paramTypes = fnDef.params.map((p, i) => { checkParam(p, i, ctx) return p.type! diff --git a/src/std/future.no b/src/std/future.no index 84df01d5..9f0a01bd 100644 --- a/src/std/future.no +++ b/src/std/future.no @@ -21,16 +21,32 @@ impl Future { Future(f, [], Created()) } - pub fn onResolve(self, f: |T|: Unit): Self { + pub fn onResolve(self, f: |T|: Unit): Unit { match self.state { Resolved(value) { f(value) - return self + return unit + } + Created() { + self.spawn(runtime) } _ {} } self.subscribers.add(f) - self + } + + // TODO: belongs to std::control::Functor + pub fn map(self, f: |T|: U): Future { + // TODO: use .await + Future::new(|resolve| self.onResolve(|res| resolve(f(res)))) + } + + // TODO: belongs to std::control::Monad + pub fn flatMap(self, f: |T|: Future): Future { + // TODO: use .await + Future::new(|resolve| { + self.onResolve(|res| f(res).onResolve(|inner| resolve(inner))) + }) } pub fn spawn(self, runtime: Runtime): Self { @@ -45,6 +61,8 @@ pub type Runtime( pending: List>, ) +pub let runtime: Runtime = Runtime::new() + impl Runtime { pub fn new(): Runtime { Runtime::withPollingRate(10)