如何更新其中包含另一条记录的记录?

时间:2017-01-07 09:31:11

标签: elm

我有一个记录:

type alias Point = {x : Int, y : Int}

我有另一张这样的记录:

type alias SuperPoint = {p : Point, z : Int}

p = Point 5 10
sp = SuperPoint p 15

现在,如果我需要更新SuperPoint.z,我可以这样做:

{sp | z = 20}

如何更新SuperPoint.Point?

2 个答案:

答案 0 :(得分:3)

sp2 =
    let
        p2 = { p | x = 42 }
    in
        { sp | p = p2 }

答案 1 :(得分:0)

目前您有四种更新方式:

  • 您可以在下面的代码
  • 中找到其中两个
  • 第三是使用Monocle
  • 第四名:Re-structure your model with Dictionaries并以适当的通用方式处理更新
  • 最后还有一个代码不起作用,但如果那样工作可能会有用

elm-0.18中的示例

Product product = new Product();

product.Name = "Apple";
product.ExpiryDate = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string output = JsonConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "ExpiryDate": "2008-12-28T00:00:00",
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}
                                            //check the generics on class Product
Product deserializedProduct = JsonConvert.DeserializeObject<Product>  (output);

来自https://groups.google.com/forum/#!topic/elm-discuss/CH77QbLmSTk

的示例
import Html exposing (..)


model =
    { left = { x = 1 }
    }


updatedModel =
    let
        left =
            model.left

        newLeft =
            { left | x = 10 }
    in
        { model | left = newLeft }


updateLeftX x ({ left } as model) =
    { model | left = { left | x = x } }


updatedModel2 =
    updateLeftX 11 model


main =
    div []
        [ div [] [ text <| toString model ]
        , div [] [ text <| toString updatedModel ]
        , div [] [ text <| toString updatedModel2 ]
        ]