Why is this function annotated like this?

I’m learing Elm and trying to understand how type annotations for generic functions are written. (Not sure “generic function” this is the right term for this in Elm, please advise.)

Given the following code:

import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)

type Msg = EmailChanged String | PasswordChanged String

formView label msg = div [] [text (label ++ ": "), input [onInput msg] []]

main = div [] [formView "Email" EmailChanged, formView "Password" PasswordChanged]

What is the reasoning behind the formView function being annotated like this

formView : String -> (String -> msg) -> Html msg

and what is the reasoning behind this annotation for the function not being right?

formView : String -> msg -> Html Msg

I’m pretty sure it’s because of the onInput function signature.

onInput : (String -> msg) -> Attribute msg

Some of the events produce a value and the attribute creators like onInput take a function that will receive that value produced by the event and will produce a message.

If the event doesn’t produce a value then the attribute creator will just take the message that the event will produce. onClick works like this. A view would look ok like this:

buttonView : String -> msg -> Html msg

Also, please note that the return of such functions is Html msg. The type of the output is tied to the type of the argument received.

The following:

formView : String -> msg -> Html Msg

altho, valid typewise, would mean that the second argument received would be ignored. If you use the value inside, the compiler would prompt you to change the signature to the concrete type that it will resolve to.

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.