exception - purescript - 对抛出异常的函数进行建模
问题描述
假设我有一个f
抛出异常的 Javascript 函数。
我想在 Purescript 方面将其公开为
foreign import f :: a -> Either e b
哪里e
是抛出异常的类型。
我可以通过捕获异常并f
用 的构造函数包装结果来实现这一点Either
,但这似乎是一个肮脏的解决方案,因为我会在 Javascript 端使用 Purescript 数据构造函数。
有没有更好或更标准的解决方案?
解决方案
从 JavaScript 构造 PureScript 数据的常用方法是将构造函数作为函数传入。你的 JS 函数需要额外的两个参数:
// JavaScript
exports.f_ = left => right => a => {
try { return right(whatever(a)); }
catch(e) { return left(e); }
}
然后在 PureScript 中导入函数,但不要将其导出给消费者。相反,制作一个传递Left
andRight
构造函数的包装器,然后导出它:
-- 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
推荐阅读
- php - 用 $j 为 php 7.2 重写字符串
- razor - asp.net core 2.1 在验证摘要中显示 HTML
- go - 如何在 golang 中获取 func 文档?
- php - 带有某些字符串的 var_dump 上的 PHP 转储不同的字符串
- php - foreach 循环动态更新中的 PHP 数学
- android - 棉花糖上的 NoActionBar
- c - 为什么代码给我错误的三角形?
- angular - NGRX Store adapter.updateone 不更改更改检测的属性
- android - Firebase Cloud Messaging:即使应用程序终止,也能从消息中解析数据
- express - 启用 CORS 模块的请求资源上不存在“Access-Control-Allow-Origin”标头