【问题标题】:How do I update an item within a list and maintain its index?如何更新列表中的项目并维护其索引?
【发布时间】:2017-07-22 17:36:11
【问题描述】:

如何更新列表中的项目?

我尝试了以下方法:

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
            []

函数 update 的第二个参数导致不匹配。

59| Dict.update 索引(只需 { 链接 | isFeatured = isFeatured }) 字典 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 功能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
       }

但它是:

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

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

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

【问题讨论】:

    标签: elm


    【解决方案1】:

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

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

    说实话,我不明白您的代码中的 isFeatured 是什么,但我假设您想在 link.title 匹配时将其更新为 True。

    【讨论】:

    • 没关系:)
    【解决方案2】:

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

    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 }]
    

    我还应该指出,如果排序很重要,更可靠的方法是在您的记录中添加一个索引字段,并在必要时对列表进行排序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-12
      • 1970-01-01
      • 1970-01-01
      • 2012-03-28
      • 1970-01-01
      相关资源
      最近更新 更多