如何更新列表中的项目并维护其索引?

时间:2017-07-22 17:36:12

标签: elm

如何更新列表中的项目?

我尝试了以下内容:

[HttpGet]
public HttpResponseMessage GetCompanies()
{

     var resp = new HttpResponseMessage { Content = new 
    StringContent("[{\"Name\":\"ABC\"},[{\"A\":\"1\"},{\"B\":\"2\"},
    {\"C\":\"3\"}]]", System.Text.Encoding.UTF8, "application/json") };


    resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
    return resp;
}
  

函数setFeaturedLink links link = let dictionary = Dict.fromList links result = Dict.filter (\k v -> v.title == link.title) dictionary |> Dict.toList |> List.head index = case result of Just kv -> let ( i, _ ) = kv in i Nothing -> -1 in if not <| index == -1 then Dict.update index (Just { link | isFeatured = isFeatured }) dictionary |> Dict.values else [] 的第二个参数导致不匹配。

     

59 | Dict.update索引(Just {link |   isFeatured = isFeatured})字典                                                      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^函数update期待   第二个参数是:

update
     

但它是:

Maybe
    { contentType : ContentType
    , profile : Profile
    , title : Title
    , topics : List Topic
    , url : Url
    , isFeatured : Bool
    }
-> Maybe
       { contentType : ContentType
       , isFeatured : Bool
       , profile : Profile
       , title : Title
       , topics : List Topic
       , url : Url
       }
     

提示:看起来函数需要多一个参数。

是否有一个简单的例子说明如何更新列表中的任意项?

2 个答案:

答案 0 :(得分:3)

是的,您只需map指向具有更新值的链接的链接:

let
  updateLink l =
    if l.title == link.title then
      { l | isFeatured = True }
    else
      l
in
  List.map updateLink links

说实话,我不明白你的代码中有isFeatured是什么,但是如果link.title匹配,我想你想把它更新为True。

答案 1 :(得分:1)

  

是否有一个简单的例子说明如何更新列表中的任意项?

this这样的东西,它基于你提供的代码而松散:

import Html exposing (text)
import List

type alias Thing = { title: String, isFeatured: Bool }

bar = (Thing "Bar" False)

things = [(Thing "Foo" False), 
         bar]

featureThing things thing = 
  List.map (\x -> if x.title == thing.title 
                    then { x | isFeatured = True} 
                    else x) 
           things

updatedThings = featureThing things bar

main =
  text <| toString updatedThings
  -- [{ title = "Foo", isFeatured = False },
  --  { title = "Bar", isFeatured = True }]

我还应该注意,如果排序很重要,更强大的方法是在您的记录中添加索引字段,并在必要时对列表进行排序。