Mercurial > repos > other > SevenLanguagesInSevenWeeks
comparison 7-Haskell/day2.hs @ 90:c27c87cd0f08
Add most of the Day 2 exercises for Haskell
author | IBBoard <dev@ibboard.co.uk> |
---|---|
date | Sun, 16 Jun 2019 21:09:33 +0100 |
parents | |
children | 075ff4e4feaf |
comparison
equal
deleted
inserted
replaced
89:7e4afb129bef | 90:c27c87cd0f08 |
---|---|
1 module Day2 where | |
2 -- We could just "import Data.List" and then use "sort", but let's do it by hand with an ugly O(n^2) approach | |
3 my_sort :: Ord a => [a] -> [a] | |
4 my_sort lst = my_sort' (<) lst [] | |
5 | |
6 -- my_sort' :: Ord a => [a] -> [a] -> [a] | |
7 -- my_sort' [] res = res | |
8 -- my_sort' (h:t) [] = my_sort' t [h] | |
9 -- my_sort' (h:t) (h_res:t_res) | |
10 -- | h < h_res = my_sort' t (h:h_res:t_res) | |
11 -- | otherwise = my_sort' t (h_res:my_sort' (h:[]) t_res) | |
12 | |
13 my_sort' :: Ord a => (a -> a -> Bool) -> [a] -> [a] -> [a] | |
14 my_sort' cmp [] res = res | |
15 my_sort' cmp (h:t) [] = my_sort' cmp t [h] | |
16 my_sort' cmp (h:t) (h_res:t_res) | |
17 | cmp h h_res = my_sort' cmp t (h:h_res:t_res) | |
18 | otherwise = my_sort' cmp t (h_res:my_sort' cmp (h:[]) t_res) | |
19 | |
20 parse_int :: String -> Int | |
21 parse_int str = parse_int' str 0 | |
22 | |
23 parse_int' :: String -> Int -> Int | |
24 parse_int' "" val = val | |
25 parse_int' (h:t) val | |
26 | fromEnum h >= 48 && fromEnum h <= 57 = parse_int' t (val * 10 + ((fromEnum h) - 48)) | |
27 | otherwise = parse_int' t val | |
28 | |
29 every_three :: Integer -> [Integer] | |
30 every_three = every_n 3 | |
31 | |
32 every_five :: Integer -> [Integer] | |
33 every_five = every_n 5 | |
34 | |
35 every_n :: Integer -> Integer -> [Integer] | |
36 every_n n x = [x, x + n ..] | |
37 | |
38 -- Usage: every_m_n (every_five) 5 (every_three) 3 | |
39 every_m_n :: (Integer -> [Integer]) -> Integer -> (Integer -> [Integer]) -> Integer -> [Integer] | |
40 every_m_n _m x _n y = zipWith (+) (_m x) (_n y) | |
41 | |
42 halve :: Double -> Double | |
43 halve x = (/ 2) x -- It's ugly, but it's the "partially applied" version of "x / 2" - "(/ 2)" becomes an anonymous function that gets applied to x | |
44 | |
45 new_line :: String -> String | |
46 new_line x = (++ "\n") x | |
47 | |
48 -- Let's go Euclidean: https://en.wikipedia.org/wiki/Greatest_common_divisor#Euclid's_algorithm | |
49 my_gcd :: Integer -> Integer -> Integer | |
50 my_gcd a b | |
51 | a == b = a | |
52 | a > b = my_gcd (a - b) b | |
53 | otherwise = my_gcd a (b - a) | |
54 | |
55 -- Wilson's theorem seems easiest: https://en.wikipedia.org/wiki/Wilson%27s_theorem | |
56 primes :: [Integer] | |
57 primes = [x | x <- [2 ..], (gcd ((product [1 .. x-1]) + 1) x) == x] |