Skip to content

Instantly share code, notes, and snippets.

@grauwoelfchen
Created August 25, 2014 16:14
Show Gist options
  • Save grauwoelfchen/92fef02311359f636ed1 to your computer and use it in GitHub Desktop.
Save grauwoelfchen/92fef02311359f636ed1 to your computer and use it in GitHub Desktop.
Recursion with Haskell
{-# OPTIONS -Wall -Werror #-}
-- maximum' [1,2,5,4] -> 5
-- maximum' [] -> *** Exception: maximum of empty list!
maximum' :: (Ord a) => [a] -> a
maximum' [] = error "maximum of empty list!"
maximum' [x] = x
maximum' (x:xs) = max x (maximum' xs)
-- replicate' 3 'a' -> "aaa"
-- replicate' 0 'b' -> ""
replicate' :: Int -> a -> [a]
replicate' n x
| n <= 0 = []
| otherwise = x : replicate' (n-1) x
-- take' 3 [1,1,1,1,1,1] -> [1,1,1]
-- take' 0 ['a','b','c'] -> ""
take' :: Int -> [a] -> [a]
take' n _
| n <= 0 = []
take' _ [] = []
take' n (x:xs) = x : take' (n-1) xs
-- reverse' [1,2,3,4,5] -> [5,4,3,2,1]
-- reverse' [] -> []
reverse' :: [a] -> [a]
reverse' [] = []
reverse' (x:xs) = reverse' xs ++ [x]
-- take 3 (repeat' 1) -> [1,1,1]
repeat' :: a -> [a]
repeat' x = x : repeat' x
-- zip' [1,2,3] [4,5,6] -> [(1,4),(2,5),(3,6)]
-- zip' ['a','b','c'] ['d'] -> [('a','d')]
zip' :: [a] -> [b] -> [(a,b)]
zip' _ [] = []
zip' [] _ = []
zip' (x:xs) (y:ys) = (x,y) : zip' xs ys
-- elem' 2 [1,2,3,4,5] -> True
-- elem' 1 [3,4,5] -> False
-- elem' 3 [] -> False
elem' :: (Eq a) => a -> [a] -> Bool
elem' _ [] = False
elem' a (x:xs)
| a == x = True
| otherwise = elem' a xs
-- quicksort [1,29,10,23,35,92,22,11] -> [1,10,11,22,23,29,35,92]
-- quicksort [] -> []
quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) =
let smallerOrEqual = [a | a <- xs, a <= x]
larger = [a | a <- xs, a > x]
in quicksort smallerOrEqual ++ [x] ++ quicksort larger
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment