首页 > 解决方案 > purescript - 对抛出异常的函数进行建模

问题描述

假设我有一个f抛出异常的 Javascript 函数。

我想在 Purescript 方面将其公开为

foreign import f :: a -> Either e b

哪里e是抛出异常的类型。

我可以通过捕获异常并f用 的构造函数包装结果来实现这一点Either,但这似乎是一个肮脏的解决方案,因为我会在 Javascript 端使用 Purescript 数据构造函数。

有没有更好或更标准的解决方案?

标签: exceptionffipurescript

解决方案


从 JavaScript 构造 PureScript 数据的常用方法是将构造函数作为函数传入。你的 JS 函数需要额外的两个参数:

// JavaScript
exports.f_ = left => right => a => {
    try { return right(whatever(a)); }
    catch(e) { return left(e); }
}

然后在 PureScript 中导入函数,但不要将其导出给消费者。相反,制作一个传递LeftandRight构造函数的包装器,然后导出

-- PureScript
module MyModule(f) where

foreign import f_ :: forall a b e. (e -> Either e b) -> (b -> Either e b) -> a -> Either e b

f :: forall a e b. a -> Either e b
f = f_ Left Right

推荐阅读