过滤列表

List.filter : (a -> Bool) -> List a -> List a 是一个高阶函数,它将一个参数函数从任何值转换为布尔值,并将该函数应用于给定列表的每个元素,仅保留函数返回 True 的元素。List.filter 作为其第一个参数的函数通常被称为谓词

import String

catStory : List String
catStory = 
    ["a", "crazy", "cat", "walked", "into", "a", "bar"]

-- Any word with more than 3 characters is so long!
isLongWord : String -> Bool
isLongWord string =
    String.length string > 3

longWordsFromCatStory : List String
longWordsFromCatStory = 
    List.filter isLongWord catStory

elm-repl 评估这个:

> longWordsFromCatStory
["crazy", "walked", "into"] : List String
>
> List.filter (String.startsWith "w") longWordsFromCatStory
["walked"] : List String