過濾列表
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