【问题标题】:How to force a function to return 'unit' in Rescript?如何强制函数在 Rescript 中返回“单位”?
【发布时间】:2022-02-07 00:32:56
【问题描述】:

我正在尝试模拟使用 rescript 写入 DB 的副作用。

所以我想在调用repository.add 时将数据推送到数组中。 Js.Array.push 返回一个 int,我不关心。我想强制返回unit,以便我的签名显示unit,这让我立即知道这个函数会产生副作用。

这里是代码(and a playground here):

module Person = {
  type entity = {
    firstName: string
  }
  
  type repository = {
    add: entity => unit,
    getAll: unit => array<entity>
  }

  
  let createRepository = (): repository => {
    let storage: array<entity> = []
    
    {
        add: entity => {
          Js.Array.push(entity, storage)  // This has type: int -> Somewhere wanted: unit
          ()         // how to force to return 'unit' there ?
       },
        getAll: () => storage
    }
  }
}

【问题讨论】:

    标签: rescript


    【解决方案1】:

    如果你像你一样返回(),函数将返回unit。这不是真正的问题。编译器抱怨的原因是您隐式忽略了Js.Array.push 返回的值,这通常是一个错误。您可以通过显式忽略它来关闭编译器:

    let _: int = Js.Array.push(entity, storage)
    

    编辑:我还要补充一点,您可能需要考虑使用更适合该范例的数据结构和 API。我可能会使用list 并将storage 改为ref&lt;list&gt;,但这有点取决于你还要用它做什么。

    【讨论】:

    • 感谢您的回答。列表可能会更好,但由于我可以使用array.filter.find(...)(不是头部或尾部)访问存储,我认为数组更适合...
    • 还有filterfind 用于list。一般来说,如果我需要索引访问或与接受或返回数组的绑定直接交互,我只会使用数组。
    猜你喜欢
    • 1970-01-01
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    • 2012-05-06
    • 1970-01-01
    • 1970-01-01
    • 2019-02-25
    相关资源
    最近更新 更多