-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHelpWithMath.hs
43 lines (33 loc) · 1.14 KB
/
HelpWithMath.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
module HelpWithMath where
faculty :: Int -> Int
faculty 0 = 1
faculty n = n * faculty (n - 1)
triangular :: Int -> Int
triangular n = (n * (n + 1) `div` 2)
-- Help with lists
inList :: Eq a => a -> [a] -> Bool
inList a [] = False
inList a (x:xs) = (a == x) || inList a xs
find :: Eq a => a -> [(a,b)] -> [b]
find x tuples = [ b | (a,b) <- tuples, a == x ]
remove :: Eq a => a -> [a] -> [a]
remove x list = [ a | a <- list, a /= x ]
--- Chopping
-- Unfold
unfold :: (a -> Bool) -> (a -> b) -> (a -> a) -> a -> [b]
unfold p h t x | p x = []
| otherwise = h x : unfold p h t (t x)
chop :: Int -> [a] -> [[a]]
chop n = unfold null (take n) (drop n)
-- Counting occurences
count n xs ys = all (\s -> s == n) (map (\x -> sum [ 1 | y <- ys, y == x ]) xs)
-- Unique elements (is 'nub': https://downloads.haskell.org/~ghc/6.12.1/docs/html/libraries/base-4.2.0.0/src/Data-List.html#nub)
uniq :: Eq a => [a] -> [a]
uniq list = uniq' list []
where
uniq' [] _ = []
uniq' (x:xs) ls | x `elem` ls = uniq' xs ls
| otherwise = x : uniq' xs (x:ls)
-- Reversing a tuple
swap :: (a,b) -> (b,a)
swap (a,b) = (b,a)