]> gitweb.michael.orlitzky.com - spline3.git/blob - src/Misc.hs
Add the 'disjoint' function.
[spline3.git] / src / Misc.hs
1 -- | The Misc module contains helper functions that seem out of place
2 -- anywhere else.
3 module Misc
4 where
5
6 import Data.List (intersect)
7
8
9 -- | The standard factorial function. See
10 -- <http://www.willamette.edu/~fruehr/haskell/evolution.html> for
11 -- possible improvements.
12 --
13 -- Examples:
14 --
15 -- >>> factorial 0
16 -- 1
17 --
18 -- >>> factorial 4
19 -- 24
20 --
21 factorial :: Int -> Int
22 factorial n
23 | n <= 1 = 1
24 | n > 20 = error "integer overflow in factorial function"
25 | otherwise = product [1..n]
26
27
28 -- | Takes a three-dimensional list, and flattens it into a
29 -- one-dimensional one.
30 --
31 -- Examples:
32 --
33 -- >>> flatten [ [[1,2], [3,4]], [[5,6], [7,8]] ]
34 -- [1,2,3,4,5,6,7,8]
35 --
36 flatten :: [[[a]]] -> [a]
37 flatten xs = concat $ concat xs
38
39
40 -- | Switch the x and z dimensions of a three-dimensional list.
41 transpose_xz :: [[[a]]] -> [[[a]]]
42 transpose_xz [] = []
43 transpose_xz [[]] = [[]]
44 transpose_xz [[[]]] = [[[]]]
45 transpose_xz m =
46 [[[ m !! x !! y !! z | x <- [0..xsize]]
47 | y <- [0..ysize]]
48 | z <- [0..zsize]]
49 where
50 zsize = (length m) - 1
51 ysize = length (head m) - 1
52 xsize = length (head $ head m) - 1
53
54 -- | Takes a list, and returns True if its elements are pairwise
55 -- equal. Returns False otherwise.
56 all_equal :: (Eq a) => [a] -> Bool
57 all_equal xs =
58 all (== first_element) other_elements
59 where
60 first_element = head xs
61 other_elements = tail xs
62
63
64 -- | Returns 'True' if the lists xs and ys are disjoint, 'False'
65 -- otherwise.
66 --
67 -- Examples:
68 --
69 -- >>> disjoint [1,2,3] [4,5,6]
70 -- True
71 --
72 -- >>> disjoint [1,2,3] [3,4,5]
73 -- False
74 --
75 disjoint :: (Eq a) => [a] -> [a] -> Bool
76 disjoint xs ys =
77 intersect xs ys == []