Prelude
8 methodsHaskell Prelude 核心函数集合。
putStrLn :: String -> IO ()打印字符串并换行。
Parameters
| Name | Type | Description |
|---|---|---|
| string | String | 待打印字符串 |
Returns
IO (),IO 动作
Example
haskell
main :: IO ()
main = do
putStrLn "Hello, Haskell"
putStrLn "line 2"map :: (a -> b) -> [a] -> [b]将函数应用到列表每个元素。
Parameters
| Name | Type | Description |
|---|---|---|
| function | a -> b | 映射函数 |
| list | [a] | 输入列表 |
Returns
[b],映射结果列表
Example
haskell
map (*2) [1,2,3] -- [2,4,6]
map reverse ["ab","cd"] -- ["ba","dc"]filter :: (a -> Bool) -> [a] -> [a]保留满足谓词的元素。
Parameters
| Name | Type | Description |
|---|---|---|
| predicate | a -> Bool | 谓词函数 |
| list | [a] | 输入列表 |
Returns
[a],过滤后列表
Example
haskell
filter even [1..6] -- [2,4,6]
filter (>3) [1,2,3,4,5] -- [4,5]foldl :: (b -> a -> b) -> b -> [a] -> b从左向右折叠列表。
Parameters
| Name | Type | Description |
|---|---|---|
| function | b -> a -> b | 折叠函数 |
| initial | b | 初始累加值 |
| list | [a] | 输入列表 |
Returns
b,折叠结果
Example
haskell
foldl (+) 0 [1,2,3,4] -- 10
foldl (\acc x -> acc ++ [x]) [] [1,2,3]
-- [1,2,3](++) :: [a] -> [a] -> [a]拼接两个列表。
Parameters
| Name | Type | Description |
|---|---|---|
| list1 | [a] | 前半列表 |
| list2 | [a] | 后半列表 |
Returns
[a],拼接后的列表
Example
haskell
[1,2] ++ [3,4] -- [1,2,3,4]
"Hello, " ++ "Haskell" -- "Hello, Haskell"head :: [a] -> a / tail :: [a] -> [a]head 返回列表首元素,tail 返回除首元素外的剩余部分。
Parameters
| Name | Type | Description |
|---|---|---|
| list | [a] | 非空列表 |
Returns
a 或 [a]
Example
haskell
head [1,2,3] -- 1
tail [1,2,3] -- [2,3]length :: [a] -> Int返回列表长度。
Parameters
| Name | Type | Description |
|---|---|---|
| list | [a] | 输入列表 |
Returns
Int,元素个数
Example
haskell
length [1,2,3,4] -- 4
length "hello" -- 5(>>=) :: Monad m => m a -> (a -> m b) -> m bMonad 的 bind 操作,串联 monadic 计算。
Parameters
| Name | Type | Description |
|---|---|---|
| monad | m a | monadic 值 |
| function | a -> m b | 续延函数 |
Returns
m b,串联后的 monadic 值
Example
haskell
justThree :: Maybe Int
justThree = Just 5 >>= \x -> Just (x - 2)
-- Just 3
[1,2] >>= \x -> [x, x*10]
-- [1,10,2,20]