Created
August 1, 2014 20:18
-
-
Save JulianBirch/64184082bd9f0aaaf822 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
{-# OPTIONS_GHC -Wall #-} | |
import Data.List | |
fun1 :: [Integer] -> Integer | |
fun1 [] = 1 | |
fun1 (x:xs) | |
| even x = (x - 2) * fun1 xs | |
| otherwise = fun1 xs | |
fun1' :: [Integer] -> Integer | |
fun1' = product . map ((-) 2) . filter even | |
fun2 :: Integer -> Integer | |
fun2 1 = 0 | |
fun2 n | |
| even n = n + fun2 (n `div` 2) | |
| otherwise = fun2 (3 * n + 1) | |
f :: Integer -> Integer | |
f 1 = 0 | |
f n | |
| even n = n `div` 2 | |
| otherwise = 3 * n + 1 | |
fun2' :: Integer -> Integer | |
fun2' = sum . takeWhile (> 1) . iterate f | |
-- iterate, takewhile | |
data Tree a = Leaf | |
| Node Integer (Tree a) a (Tree a) | |
deriving (Show, Eq) | |
height :: Tree a -> Integer | |
height Leaf = 0 | |
height (Node h _ _ _) = h | |
addToTree :: a -> Tree a -> Tree a | |
addToTree a Leaf = Node 1 Leaf a Leaf | |
addToTree a (Node h n1 b n2) | |
| height n1 > height n2 = Node h n1 b (addToTree a n2) | |
| True = let n@(Node hnew _ _ _) = (addToTree a n1) | |
newHeight = (max (hnew + 1) h) | |
in Node newHeight n b n2 | |
foldTree :: [a] -> Tree a | |
foldTree = foldr addToTree Leaf | |
xor :: [Bool] -> Bool | |
xor = foldr (/=) False | |
map' :: (a -> b) -> [a] -> [b] | |
map' = flip foldr [] . ((:) .) | |
myFoldl :: (a -> b -> a) -> a -> [b] -> a | |
myFoldl f z l = foldr (flip f) z (reverse l) | |
cartProd :: [a] -> [b] -> [(a, b)] | |
cartProd xs ys = [(x,y) | x <- xs, y <- ys] | |
sieveSundaram :: Integer -> [Integer] | |
sieveSundaram n = let f (i,j) = i + j + 2 * i * j | |
g n = 2 * n + 1 | |
h = map f $ cartProd [1..n] [1..n] | |
in map g $ [1..n] \\ h |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment