基于另一条记录更新模型中的记录

时间:2015-12-22 09:52:50

标签: elm

我有这样的事情:

type alias Record = 
    { id : String
    , nextId : String
    , value : String
    , result : Int
    }

type alias Model = List Record
model = [
    {
        ...
    },
    ...
]

...

update id model =
    List.map (updateRecord id) model

updateRecord id record =
    if record.id == id then
        {record | result = 1}
    else
        record

基本上,当我使用update调用id时,我需要的是使用id(我已经拥有的那部分)更新记录,但也从记录中获取值#39 ; s nextId,找到record.id == nextId的另一条记录,并将value从第一条记录传递到第二条记录

基本上我在寻找用JS编写的内容:

function update(id, model) {
    var nextId, value;
    var newModel1 = model.map(function(record) {
        if (record.id === id) {
            record.result = 1;
            nextId = record.nextId;
            value = record.value;
            return record;
        } else {
            return record;
        }
    });

    var newModel2 = model.map(function(record) {
        if (record.id === nextId) {
            record.value = value;
            return record;
        } else {
            return record;
        }
    });

    return newModel2;
} 

我如何实现它?

1 个答案:

答案 0 :(得分:0)

这应该给你你想要的东西:

type alias UpdateNext = 
  { nextId : String
  , value : String
  }

update id model =
  let
    (matchedModel, nextToUpdate) = match id model
  in
    case nextToUpdate of
      Nothing ->
        model
      Just next ->
        updateNext next matchedModel

match : String -> Model -> (Model, Maybe UpdateNext)
match id model =
  case model of
    [] ->
      ([], Nothing)
    (x::xs) ->
      if x.id == id then
        ( { x | result = 1 } :: xs
        , Just { nextId = x.nextId, value = x.value }
        )
      else
        let (ys, updateNext) = match id xs
        in (x :: ys, updateNext)

updateNext : UpdateNext -> Model -> Model
updateNext next model =
  case model of
    [] ->
      []
    (x::xs) ->
      if x.id == next.nextId then
        { x | value = next.value } :: xs
      else
        x :: updateNext next xs

这比List.map更有效,因为它在匹配结果时会短路处理。