在学习haskell 记录以下常用的函数
随时更新!
span
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 中 第一个不符合条件的元素开始的剩余的元素的list
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])
maybe
maybe :: b -> (a -> b) -> Maybe a -> b
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.
maybe 方法设置一默认值 一个 函数 和 一个 maybe 值,如果 maybe 值 是Nothing,函数返回默认值,否则,返回 将Just 值传入函数中的结果
> 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