Haskell 编写几个递归函数 练习 typeclass 模式匹配等
Posted vlyf
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Haskell 编写几个递归函数 练习 typeclass 模式匹配等相关的知识,希望对你有一定的参考价值。
-- 取list中的最大值
maxiMum' :: (Ord a) => [a] -> a
maxiMum' [] = error "Empty list"
maxiMum' [x] = x
maxiMum' (x:xs)
| x > maxTail = x
| otherwise = maxTail
where maxTail = maxiMum' xs
maxiMum1' :: (Ord a) => [a] -> a
maxiMum1' [] = error "Empty list"
maxiMum1' [x] = x
maxiMum1' (x:xs) = max x (maxiMum1' xs)
-- 构建含n个x的list
replicate' :: (Num i, Ord i) => i -> a -> [a]
replicate' n x
| n <= 0 = []
| otherwise = x:replicate' (n-1) x
-- 取list前n个
take' :: (Num i, Ord i) => i -> [a] -> [a]
take' n _
| n <= 0 = []
take' _ [] = []
take' n (x:xs) = x : take' (n-1) xs
-- 反转list
reverse' :: [a] -> [a]
reverse' [] = []
reverse' (x:xs) = reverse' xs ++ [x]
以上是关于Haskell 编写几个递归函数 练习 typeclass 模式匹配等的主要内容,如果未能解决你的问题,请参考以下文章