]> gitweb.michael.orlitzky.com - spline3.git/blob - Misc.hs
16b0ead151ad1b29190028db01aa98ef34d6b797
[spline3.git] / 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 import Test.Framework (Test, testGroup)
8 import Test.Framework.Providers.HUnit (testCase)
9 import Test.Framework.Providers.QuickCheck2 (testProperty)
10 import Test.HUnit
11 import Test.QuickCheck
12
13
14 -- | The standard factorial function. See
15 -- <http://www.willamette.edu/~fruehr/haskell/evolution.html> for
16 -- possible improvements.
17 --
18 -- Examples:
19 --
20 -- >>> factorial 0
21 -- 1
22 --
23 -- >>> factorial 4
24 -- 24
25 --
26 factorial :: Int -> Int
27 factorial n
28 | n <= 1 = 1
29 | n > 20 = error "integer overflow in factorial function"
30 | otherwise = product [1..n]
31
32
33 -- | Takes a three-dimensional list, and flattens it into a
34 -- one-dimensional one.
35 --
36 -- Examples:
37 --
38 -- >>> flatten [ [[1,2], [3,4]], [[5,6], [7,8]] ]
39 -- [1,2,3,4,5,6,7,8]
40 --
41 flatten :: [[[a]]] -> [a]
42 flatten xs = concat $ concat xs
43
44
45 -- | Switch the x and z dimensions of a three-dimensional list.
46 transpose_xz :: [[[a]]] -> [[[a]]]
47 transpose_xz [] = []
48 transpose_xz [[]] = [[]]
49 transpose_xz [[[]]] = [[[]]]
50 transpose_xz m =
51 [[[ m !! x !! y !! z | x <- [0..xsize]]
52 | y <- [0..ysize]]
53 | z <- [0..zsize]]
54 where
55 zsize = (length m) - 1
56 ysize = length (head m) - 1
57 xsize = length (head $ head m) - 1
58
59 -- | Takes a list, and returns True if its elements are pairwise
60 -- equal. Returns False otherwise.
61 all_equal :: (Eq a) => [a] -> Bool
62 all_equal xs =
63 all (== first_element) other_elements
64 where
65 first_element = head xs
66 other_elements = tail xs
67
68
69 -- | Returns 'True' if the lists xs and ys are disjoint, 'False'
70 -- otherwise.
71 --
72 -- Examples:
73 --
74 -- >>> disjoint [1,2,3] [4,5,6]
75 -- True
76 --
77 -- >>> disjoint [1,2,3] [3,4,5]
78 -- False
79 --
80 disjoint :: (Eq a) => [a] -> [a] -> Bool
81 disjoint xs ys =
82 intersect xs ys == []
83
84
85
86 prop_factorial_greater :: Int -> Property
87 prop_factorial_greater n =
88 n <= 20 ==> factorial n >= n
89
90
91 test_flatten1 :: Assertion
92 test_flatten1 =
93 assertEqual "flatten actually works" expected_list actual_list
94 where
95 target = [[[1::Int]], [[2, 3]]]
96 expected_list = [1, 2, 3]
97 actual_list = flatten target
98
99
100 misc_tests :: Test.Framework.Test
101 misc_tests =
102 testGroup "Misc Tests" [
103 testCase "flatten (1)" test_flatten1 ]
104
105
106 misc_properties :: Test.Framework.Test
107 misc_properties =
108 testGroup "Misc Properties" [
109 testProperty "factorial greater" prop_factorial_greater ]