Elm: How to create a view that doesn't return Msg?

北战南征 提交于 2019-12-11 02:37:16

问题


Currently, I have a nested component that only shows an error text. The view method receives a Model and returns Html, but the compiler complains saying that Html needs another value, so I ended up doing this:

view: Model -> Html ()
view error =
    div [class "docs-section error-bar"] [
      errorText error
    ]

errorText: Model -> Html ()
errorText error =
  case error.text of
    Nothing -> span [][]
    Just value -> text value

What I don't like is that I have to add the () value to the signature. Is there a way I can get rid of this?

Thanks!


回答1:


The Html type requires exactly one parameter, so you always have to give is something. Using () as a type parameter is a common way to put a dummy value there.

You could always define a type alias to avoid typing () every time:

type alias OnlyHtml = Html ()

Then you could change your type signatures appropriately:

view: Model -> OnlyHtml



回答2:


Using Html () will make it harder for you to compose this view with views that do send messages. Instead, use a type variable: view: Model -> Html msg.

The lowercase m is critically important: it means that this HTML can send any kind of message. Except that, sending a message of unknown type would break the type system, so instead it must not send any messages. If this seems strange, consider that x : List a means that the elements of x are of arbitrary type, and therefore there are no such elements: x == [].

Using the type variable is the most general type for your functions. All you're doing by using () instead is giving a more specific annotation, which is allowed. It's like claiming the empty list is actually a list of strings: sure, but all you've done is made that value unacceptable to a function that expects a list of another type. This is what I mean by Html () is hard to compose without other views.

viewMsg : Html Msg
viewUnit : Html ()
viewTypeVariable : Html msg

views = [viewMsg, viewTypeVariable] -- This is okay
views = [viewMsg, viewUnit] -- This is a type error!


来源:https://stackoverflow.com/questions/37257407/elm-how-to-create-a-view-that-doesnt-return-msg

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!