轉換列表的每個元素

List.map : (a -> b) -> List a -> List b 是一個高階函式,它將單引數函式應用於列表的每個元素,返回帶有修改值的新列表。

import String

ourList : List String
ourList = 
    ["wubba", "lubba", "dub", "dub"]

lengths : List Int
lengths = 
    List.map String.length ourList
-- [5,5,3,3]

slices : List String
slices =
    List.map (String.slice 1 3) ourList
-- ["ub", "ub", "ub", "ub"]

如果你需要知道元素的索引,可以使用 List.indexedMap : (Int -> a -> b) -> List a -> List b

newList : List String
newList =
    List.indexedMap (\index element -> String.concat [toString index, ": ", element]) ourList
-- ["0: wubba","1: lubba","2: dub","3: dub"]