thinking in haskell-函数

2018-09-14  本文已影响3人  funcx

Haskell没有变量,只有表达式,所以不能定义变量,表达式即是函数,在纯函数的情况下,相同的输入得到相同的输出,不能定义变量也就不能使用for,while等循环控制语句.
遍历一个数组就要用到模式匹配

-- 模式匹配
sum' [] = 0
sum' (x:xs) = x + sum' xs

-- case(可进行模式匹配)
sum'' :: [Int] -> Int
sum'' xs = case xs of [] -> 0
                      (x:xs) -> x + (sum'' xs)

-- 守卫(不可进行模式匹配)
guard a 
    | a ==1  = "a"
    | a ==2  = "b"
    | otherwise = "i don't know"
-- 递归查找数组的最大值(1)
maximum' :: (Ord a) => [a] -> a
maximum' []  = error "list is null"
maximum' [x] = x
maximum' (x:xs)
        | x > maxTail = x
        | otherwise = maxTail
        where maxTail = maximum' xs

-- 递归查找数组的最大值(2)
maximum'' :: (Ord a) => [a] -> a
maximum'' [] = error "list is null"
maximum'' [x] = x
maximum'' (x:xs) = max x (maximum'' xs)

-- 将a重复i次返回列表
replicate' :: (Ord i, Num i) => i -> a -> [a]
replicate' n x 
           | n <= 0 = []
           | otherwise = x : replicate' (n - 1) x

-- 取列表的前n个,返回一个列表
take' :: Int -> [a] -> [a]
take' _ [] = []
take' n _
      | n <= 0 = []
take' n (x:xs) = x:take' (n-1) xs

-- 反转列表
reverse' :: [a] -> [a]
reverse' [] = []
reverse' (x:xs) = (reverse' xs) ++ [x]

-- 无限循环列表
repeat' :: a -> [a]
repeat' a = a:repeat' a

-- 将两个列表组合成一个元素为元祖的列表
zip' :: [a] -> [b] -> [(a,b)]
zip' _ [] = []
zip' [] _ = []
zip' (x:xs) (y:ys) = (x,y):zip' xs ys

-- 检查元素是否在列表中
elem' :: (Eq a) => a -> [a] ->Bool
elem' _ [] = False
elem' a (x:xs)
      | a == x = True
      | otherwise = a `elem'` xs

-- 快速排序
quickSort :: (Ord a) => [a] -> [a]
quickSort [] = []
quickSort (x:xs) =
          let smallerSorted = quickSort [a | a <- xs, a <= x] 
              biggerSorted = quickSort [a | a <- xs, a > x] 
          in smallerSorted ++ [x] ++ biggerSorted

-- 列表长度
len :: [a] -> Int
len [] = 0
len (x:xs) = 1 + len xs
上一篇下一篇

猜你喜欢

热点阅读