In Elm qual è il modo corretto di prendere il mio Modello e implementare una funzione toString?In Elm qual è il modo corretto per implementare il mio toString
Il tipo che sto cercando sarebbe toString : Model -> String
, sono in grado di eseguire una funzione simile con il tipo di toStr : Model -> String
ma credo che vorrei che la funzione venisse chiamata toString
.
Esempio di programma (il Coin Changer kata):
module CoinChanger where
import Html exposing (..)
import StartApp.Simple as StartApp
import Signal exposing (Address)
import Html.Attributes exposing (..)
import Html.Events exposing (on, targetValue)
import String
---- MAIN ----
main =
StartApp.start
{
model = emptyModel
,update = update
,view = view
}
---- Model ----
type alias Model =
{
change : List Int
}
emptyModel : Model
emptyModel =
{
change = []
}
---- VIEW ----
toStr : Model -> String
toStr model =
model.change
|> List.map (\coin -> (toString coin) ++ "¢")
|> String.join ", "
view : Address String -> Model -> Html
view address model =
div []
[
input
[
placeholder "amount to make change for"
, on "input" targetValue (Signal.message address)
, autofocus True
-- style
]
[]
, div []
[
text (toStr model)
]
]
---- UPDATE ----
changeFor : Int -> List Int
changeFor amount =
[ 25, 10, 5, 1 ]
|> List.foldl
(\coin (change, amount)
-> (change ++ List.repeat (amount // coin) coin
, amount % coin)
)
([], amount)
|> fst
update : String -> Model -> Model
update change model =
{ model | change =
case String.toInt change of
Ok amount
-> changeFor amount
Err msg
-> []
}
penserei il modo corretto per farlo sarebbe quello di chiamare la funzione toString
, ma che mi dà il seguente errore del compilatore:
Errori rilevati in 1 modulo. - TIPO MISMATCH --------------------------------------------- - CoinChanger.elm
L'annotazione del tipo per
toString
non corrisponde alla sua definizione.42│ toString: Modello -> String ^^^^^^^^^^^^^^^ Il tipo di annotazione è dicendo:
{ change : List Int } -> String
ma sono dedurre che la definizione ha questo tipo:
{ change : List { change : List Int } } -> String
Rinominare la funzione di toStr
(o qualcosa non chiamato toString
) risolve il problema, ma sembra sbagliato. Qual è il modo corretto per farlo?
Ho cambiato la riga 45 in '|> List.map (\ coin -> (Moneta basics.toString) ++" ¢ ")' e tutto ha funzionato esattamente come hai detto tu . Grazie! –