haskell - recursion

Haskell is such an language that you can leverage aided with recursion, you can solve a load of issues. 

 

we will going to examine some examples which can be solved by the recursion, problem such as 

  • maximum.
  • replicate,take,reverse,repeat,zip,elem
  • quick sort
  • Think recursively

Let's see the example code below. 

 

-- recursions.hs
--  we take a close look at the recursion 

maximum' :: (Ord a) => [a] -> a
maximum' [] = error "maximum of empty list"
maximum' [x] = x
maximum' (x : xs) 
   | x > maxTail = x
   | otherwise  = maxTail 
   where maxTail = maximum' xs

-- a few more recursive functions 

-- a side note is that , guard will allow you to write condition, while 
-- pattern match do not allow condition 
replicate' :: (Num i, Ord i) => i -> a -> [a] -- i should be both a Num and a Ord 
replicate' n x 
  | n <= 0 = []
  | otherwise = x : replicate' (n - 1) x 


-- it does not mean that you cannot mix 
--  guard and pattern matching!
take' :: (Num i, Ord i) => i -> [a] -> [a]
take' n _ 
  | n <= 0 = [] -- without the otherwise, the guard will fall through to pattern match
take' _ [] = []
take' n (x :xs) = x : take' (n - 1) xs



-- reverse

reverse' :: [a] -> [a]
reverse' [] = []
reverse' (x : xs) = reverse' xs ++ [x]

-- infinite list?
--  repeat'
repeat' :: a -> [a]
repeat' x = x : repeat' x


-- zip'
-- take two lists and zips them together. zip [1,2,3] [2,3]

zip' :: [a] -> [b] -> [(a, b)]
zip' _ [] = []
zip' [] _ = []
zip' (x : xs) (y : ys) = (x, y): zip' xs ys

-- elem'
-- tell if an element exists on a list
elem' :: (Eq a) => a -> [a] -> Bool
elem' a [] = False
elem' a (x:xs)
  | a == x = True
  | otherwise = a `elem'` xs


-- quicksort
-- an quick sort implemnentation with recursion

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

-- here is guideline on the quick sort, which we called is the quick sort mentality 
--   We did quite a bit of recursion so far and as you've probably noticed, there's a pattern here. Usually you define an edge case and then you define a function that does something between some element and the function applied to the rest. It doesn't matter if it's a list, a tree or any other data structure. A sum is the first element of a list plus the sum of the rest of the list. A product of a list is the first element of the list times the product of the rest of the list. The length of a list is one plus the length of the tail of the list. Ekcetera, ekcetera ...

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值