用于安全导入 javascript 函数的纯脚本 FFI 类型

purescript FFI types to safely import javascript functions

尝试纯脚本 FFI,并按照 "Purescript By Example" 书,我创建了一个 JS 文件来获取数组的头部:

exports.head = function(arr) {
  return arr[0];
};

并且在纯脚本中,我为 head 的类型签名声明了一个新的 Undefined 数据,以指示数组为空时 undefined returned:

foreign import data Undefined :: Type -> Type
foreign import head :: forall a. Array a -> Undefined a

现在,如何使用 Undefined a 类型的值?我需要定义什么功能来 提取 a 以便我可以在其他地方使用它? 书中的例子后面只是定义了一个函数:

foreign import isUndefined :: forall a. Undefined a -> Boolean

如:

exports.isUndefined = function(value) {
  return value === undefined;
};

但我需要这样的东西:

foreign import getFromUndefined :: forall a. Undefined a -> a

是否可以用JS写那个函数,那样的话,当Undefined a真的是undefined时return怎么办? 或者,我可以重新定义类型 Undefined a 以允许对其进行模式匹配以 extract a?

你可以实现类似的东西

foreign import fromUndefinedWithDefault :: forall a. a -> Undefined a -> a

而是重用您所做的定义 isUndefined

你写的类型无法安全实现,因为我可以用它来定义

bad :: Void
bad = getFromUndefined (head [])