试图学习榆树,这很难:)
我想要完成的事情:
我的模型是具有多个键值对的记录。我想用字符串列表中的值填充这些键。
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个键需要填充,该怎么办?上面的代码会变得非常疯狂。
答案 0 :(得分:2)
您可以在列表中使用模式匹配:
populate : Model -> List String -> Model
populate model data =
case data of
one :: two :: three :: _ ->
{ model | one = one, two = two, three = three }
_ ->
model