1

我需要bind/ flatMap/>>=OptionalDhall 上。

我找不到它的实现并想出了我自己的。

let bindOptional
    : ∀(a : Type) → ∀(b : Type) → (a → Optional b) → Optional a → Optional b
    = λ(a : Type) →
      λ(b : Type) →
      λ(f : a → Optional b) →
      λ(o : Optional a) →
        Prelude.Optional.fold a o (Optional b) f (None b)

然后我按如下方式使用

bindOptional Outer Inner (λ(x : Outer) → x.inner) outer

中真的没有定义这样的功能Prelude吗?我想我可能错过了。

此外:

  1. 有没有更惯用的方式来定义它?

  2. 是否有可能利用类型推断并缩短调用时间?就像是

    bindOptional _.inner outer -- the compiler infers `Outer` from `outer` and `Inner` from `_.inner`  
    

我试图不提供类型参数,但似乎不可能(从我对语言的有限了解)。

4

1 回答 1

1

在撰写本文时Optional,Prelude 中还没有这样的操作 for,尽管没有特别的原因导致它不存在,因此您可以打开拉取请求来添加它。

最接近语言支持的机制是使用merge关键字对Optional值起作用的事实,因此这将起作用:

merge { Some = λ(_ : Inner) → _.inner, None = None SomeType } outer

…虽然这仍然需要指定InnerandSomeType类型,所以它没有利用类型推断。

于 2020-09-28T00:25:13.297 回答