Elm http 2.0.0 函数需要构造函数

Elm http 2.0.0 functions expect constructor function

对于 http request 函数,the Elm tutorial and the docs 都建议将构造函数(例如 GotText)传递给期望函数(例如 expectString),对于 expect 字段,例如:

type Msg
  = GotText (Result Http.Error String)

getPublicOpinion : Cmd Msg
getPublicOpinion =
  Http.get
    { url = "https://elm-lang.org/assets/public-opinion.txt"
    , expect = Http.expectString GotText
    }

我理解这一点,但在我看来,将 API 限制为需要构造函数(例如 GotText)过于严格。


例如可以使用identity从请求函数get中提取构造函数GotText:

getPublicOpinion = Cmd.map GotText (
  Http.get
    { url = "https://elm-lang.org/assets/public-opinion.txt"
    , expect = Http.expectString identity
    })

但这引出了一个问题:为什么 http API 完全需要构造函数*?

* 或者至少允许我们省略 expect 字段和 return Result Http.Error String.

这不是限制,实际上是方便

如果 Http.expectString 没有使用函数 (Result Http.Error String -> msg) 那么 Http.get 会 return 一个 Cmd (Result Http.Error String) 如果你传入 identity.

由于所有 Cmd 的结果始终需要是一个 Msg,运行时可以将其传递给您的 update 函数,因此您总是必须 Cmd.map每次调用 Http.getCmd (Result Http.Error String) 转换为 Cmd Msg.

的结果

为了避免每次调用 Http.get 时都必须调用 Cmd.map,API 允许您将直接进行转换的函数传递给 Http.expectString。这样打字更少,嵌套更少,因此 reader.

更清晰

您会看到这个惯例在很多模块中重复出现。例如:

  • Json.Encode.list 具有类型 list : (a -> Value) -> List a -> Value 它需要一个函数来对列表的元素进行 JSON 编码,这使您不必使用List.map 到 JSON 首先对列表的元素进行编码。

  • Html.Events.onInput 具有类型 onInput : (String -> msg) -> Attribute msg 它需要一个函数将 String 转换为 msg 值,这使您不必Html.Attribute.map onInput 的结果,将 Attribute String 转换为 Attribute msg。如果您必须为每个事件处理程序调用 Html.Attribute.map 并在任何 Html 元素上调用 Attribute,那将是一件非常痛苦的事情。