0
努力學習榆樹,這是相當困難的:)榆樹:填充一個紀錄值列表
我試圖做到:
我有一個模型,是與一些主要的紀錄值對。我想用字符串列表中的值填充這些鍵。
module Main exposing (..)
import List
import Html exposing (Html, program, div, text)
type alias Model =
{ one: String
, two: String
, three: String
}
fakeData: List String
fakeData = ["foo", "bar", "baz", "bad", "baf"]
populate: Model -> List String -> Model
populate model data =
case List.head data of
Just str ->
case model.one of
"" ->
let updatedModel =
{ model | one = str }
in
case List.tail data of
Just items ->
populate updatedModel items
Nothing ->
model
_ ->
case model.two of
"" ->
let updatedModel =
{ model | two = str }
in
case List.tail data of
Just items ->
populate updatedModel items
Nothing ->
model
_ ->
case model.three of
"" ->
let updatedModel =
{ model | three = str }
in
case List.tail data of
Just items ->
populate updatedModel items
Nothing ->
model
_ ->
model
Nothing ->
model
init: (Model, Cmd Msg)
init =
(populate { one = "", two = "", three = "" } fakeData, Cmd.none)
type Msg =
NoOp
view: Model -> Html Msg
view model =
div []
[ text (toString model) ]
update: Msg -> Model -> (Model, Cmd Msg)
update msg model =
case msg of
NoOp ->
(model, Cmd.none)
subscriptions: Model -> Sub Msg
subscriptions model =
Sub.none
main: Program Never Model Msg
main =
program
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}
這個程序打印出:
{ one = "foo", two = "bar", three = "baz" }
我想我有一個很難搞清楚如何使這個代碼少重複,更容易推理。如果我在模型中有20個鍵都需要填充,該怎麼辦?上面的代碼會變得非常瘋狂。
@ chadgilbert的答案是(一如既往)非常好。詳細闡述一下:在Elm中,記錄並非真正用於迭代。通常情況下,當你的代碼在Elm中真的被延長時,這是一個跡象表明其他事情正在發生(也許是另一種類型)。 值得看看Elm中的'Dict'類型。在你的模型中使用其中之一可能會讓事情變得更容易。 – wintvelt