Last active
May 23, 2017 09:56
-
-
Save tronje/4b48c7b1b2be422bbd6549eb04a5230d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
reverse' :: [a] -> [a] | |
reverse' [] = [] | |
reverse' xs = (last xs) : (reverse' $ init xs) | |
sort' :: Ord a => [a] -> [a] | |
sort' [] = [] | |
sort' (pivot:xs) = | |
sort' [x | x <- xs, x < pivot] | |
++ [pivot] | |
++ sort' [x | x <- xs, x >= pivot] | |
qsort :: Ord a => [a] -> [a] | |
qsort [] = [] | |
qsort xs = | |
let pos = ((length xs) `div` 2) | |
pivot = xs !! pos | |
newxs = take pos xs ++ drop (pos + 1) xs | |
in qsort [x | x <- newxs, x < pivot] | |
++ [pivot] | |
++ qsort [x | x <- newxs, x >= pivot] | |
min' :: Ord a => [a] -> a | |
min' (x:xs) = min'' x xs | |
where | |
min'' current [] = current | |
min'' current (y:ys) = | |
if y < current | |
then min'' y ys | |
else min'' current ys | |
max' :: Ord a => [a] -> a | |
max' (x:xs) = max'' x xs | |
where | |
max'' current [] = current | |
max'' current (y:ys) = | |
if y > current | |
then max'' y ys | |
else max'' current ys | |
map' :: (a -> b) -> [a] -> [b] | |
map' f [] = [] | |
map' f (x:xs) = (f x) : map' f xs | |
take' :: (Num a, Eq a) => a -> [b] -> [b] | |
take' _ [] = [] | |
take' 0 _ = [] | |
take' n (x:xs) = x : (take' (n - 1) xs) | |
drop' :: (Num a, Eq a) => a -> [b] -> [b] | |
drop' _ [] = [] | |
drop' 0 xs = xs | |
drop' n (x:xs) = drop' (n - 1) xs | |
sum' :: Num a => [a] -> a | |
sum' [] = 0 | |
sum' (x:xs) = x + sum' xs | |
product' :: Num a => [a] -> a | |
product' [] = 1 | |
product' (x:xs) = x * product' xs | |
elem' :: Eq a => a -> [a] -> Bool | |
elem' _ [] = False | |
elem' x xs = x == (head xs) || (elem x $ tail xs) | |
cycle' :: [a] -> [a] | |
cycle' xs = xs ++ (cycle' xs) | |
repeat' :: a -> [a] | |
repeat' x = x : repeat' x | |
nPrimes :: Int -> [Int] | |
nPrimes n = take n [p | p <- [1..], isPrime p] | |
isPrime :: Int -> Bool | |
isPrime n | n < 2 = False | |
isPrime 2 = True | |
isPrime n = foldl (&&) True (map (notDivisible n) [2 .. n `div` 2]) | |
where | |
notDivisible :: Int -> Int -> Bool | |
notDivisible n d = n `mod` d /= 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment