2017-07-22 52 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 }] 

我也應該注意,如果順序很重要,一個更強大的方法是添加索引字段添加到您的記錄中,並在必要時對列表進行排序。

相關問題