I am completely lost in trying to translate the following Haskell code into Javascript:
instance MonadFix IO where
mfix f = do
var <- newEmptyMVar -- 1
ans <- unsafeInterleaveIO $ takeMVar var -- 2
result <- f ans -- 3
putMVar var result -- 4
return result -- 5
Let’s walk through this line by line in terms of our little time travel analogy:
- Create an empty mutable variable.
- Predict the future value that will be contained in that mutable variable.
- Call the function f with the predicted future value.
- Store the result of f in the variable, thus fulfilling the prophecy as required by line 2.
- Return that result.
What I have is a special Lazy
type that handles (or rather defers) synchronous IO
. However, I'd like to abstract from direct recursion with value recursion:
const record = (type, o) =>
(o[Symbol.toStringTag] = type.name || type, o);
const Lazy = lazy => record(Lazy, {get lazy() {
delete this.lazy
return this.lazy = lazy();
}});
// Monad
const lazyChain = mx => fm =>
Lazy(() => fm(mx.lazy).lazy);
const lazyChain_ = fm => mx =>
Lazy(() => fm(mx.lazy).lazy);
const lazyOf = x => Lazy(() => x);
// mfix = chain_ => fm => chain_(fm) (mfix(chain_) (fm)) ???
// MAIN
const trace = x => (console.log(x), x);
const app_ = x => f => trace(f(x));
const readLine = s => Lazy(() => window.prompt(s));
const fac = x => x === 0 ? 1 : x * fac(x - 1),
tri = x => x === 0 ? 0 : x + tri(x - 1);
const foo = lazyChain(readLine("enter true/false")) (s => {
return lazyOf(s === "true"
? fac : tri);
});
const bar = x => lazyChain(foo) (y => lazyOf(app_(x) (y)));
const main = bar(5);
console.log("effect has not yet been unleashed..");
main.lazy;
How do I implement the Lazy
instance of MonadFix
in Javascript?