转换列表的每个元素

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