【问题标题】:purescript FFI types to safely import javascript functions用于安全导入 javascript 函数的 purescript FFI 类型
【发布时间】:2017-06-29 18:56:16
【问题描述】:

试用 purescript FFI,并按照“Purescript By Example”一书,我创建了一个 JS 文件来获取数组的头部:

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

在 purescript 中,我为 head 的类型签名声明了一个新的 Undefined 数据,以指示数组为空时返回的 undefined

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 时返回什么? 或者,我可以重新定义类型 Undefined a 以允许在其上进行模式匹配以提取 a?

【问题讨论】:

    标签: javascript ffi purescript


    【解决方案1】:

    你可以实现类似的东西

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

    而是通过重用你所做的来定义isUndefined

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-23
      • 2011-10-26
      • 1970-01-01
      • 2014-12-11
      • 1970-01-01
      相关资源
      最近更新 更多