haskell 經常使用 函數

在學習haskell 記錄如下經常使用的函數html

隨時更新!app

span ide

span :: (a -> Bool) -> [a] -> ([a], [a])函數

span, applied to a predicate p and a list xs, returns a tuple where first element is longest prefix (possibly empty) of xs of elements that satisfy p and second element is the remainder of the list:學習

接受一個 判斷條件 和 一個 list xs, 返回一個包含兩個list 的 元組,其中第一個是符合條件的list,第二個是包含從 list xs 中 第一個不符合條件的元素開始的剩餘的元素的listspa

span (< 3) [1,2,3,4,1,2,3,4] == ([1,2],[3,4,1,2,3,4])
span (== 1) [1,2,3] == ([1],[2,3])
span (< 0) [1,2,3] == ([],[1,2,3])

 maybecode

maybe :: b -> (a -> b) -> Maybe a -> bhtm

The maybe function takes a default value, a function, and a Maybe value. If the Maybe value is Nothing, the function returns the default value. Otherwise, it applies the function to the value inside the Just and returns the result.blog

maybe 方法設置一默認值 一個 函數 和 一個 maybe 值,若是 maybe 值 是Nothing,函數返回默認值,不然,返回 將Just 值傳入函數中的結果element

> maybe 0 (+ 42) Nothing
0
> maybe 0 (+ 42) (Just 12)
54

findIndex

 

Function find returns the first element of a list that satisfies a predicate, or Nothing, if there is no such element. findIndex returns the corresponding index. findIndices returns a list of all such indices.

返回第list中一個符合條件的元素的index, 沒有的話則返回nothing

Input: findIndex (>3) [0,2,4,6,8]

Output: Just 2
相關文章
相關標籤/搜索