2017-07-22 53 views
1

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

我试过如下:

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级以上的说法。

有没有一个简单的例子可以更新列表中的任意项目?

回答

2

是的,你可以map的链接与更新的价值环节:

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

说实话,我不明白是什么isFeatured是在你的代码,但我相信你想将它升级到如果link.title匹配,则为true。

+0

我很尴尬...... –

+0

这很好:) –

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

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

相关问题