1 -- | The Grid module just contains the Grid type and two constructors
2 -- for it. We hide the main Grid constructor because we don't want
3 -- to allow instantiation of a grid with h <= 0.
7 import Test.QuickCheck (Arbitrary(..), Gen, Positive(..))
9 import Cube (Cube(Cube))
13 import ThreeDimensional (contains_point)
16 -- | Our problem is defined on a Grid. The grid size is given by the
17 -- positive number h. The function values are the values of the
18 -- function at the grid points, which are distance h from one
19 -- another in each direction (x,y,z).
20 data Grid = Grid { h :: Double, -- MUST BE GREATER THAN ZERO!
21 function_values :: [[[Double]]] }
25 instance Arbitrary Grid where
27 (Positive h') <- arbitrary :: Gen (Positive Double)
28 fvs <- arbitrary :: Gen [[[Double]]]
29 return (make_grid h' fvs)
32 -- | The constructor that we want people to use. If we're passed a
33 -- non-positive grid size, we throw an error.
34 make_grid :: Double -> [[[Double]]] -> Grid
35 make_grid grid_size values
36 | grid_size <= 0 = error "grid size must be positive"
37 | otherwise = Grid grid_size values
40 -- | Creates an empty grid with grid size 1.
42 empty_grid = Grid 1 [[[]]]
45 -- | Returns a three-dimensional list of cubes centered on the grid
46 -- points of g with the appropriate 'FunctionValues'.
47 cubes :: Grid -> [[[Cube]]]
49 | fvs == [[[]]] = [[[]]]
50 | head fvs == [[]] = [[[]]]
52 [[[ Cube (h g) i j k (make_values fvs i j k) | i <- [0..xsize]]
56 fvs = function_values g
57 zsize = (length fvs) - 1
58 ysize = length (head fvs) - 1
59 xsize = length (head $ head fvs) - 1
62 -- | Takes a grid and a position as an argument and returns the cube
63 -- centered on that position. If there is no cube there (i.e. the
64 -- position is outside of the grid), it will return 'Nothing'.
65 cube_at :: Grid -> Int -> Int -> Int -> Maybe Cube
70 | i >= length (cubes g) = Nothing
71 | j >= length ((cubes g) !! i) = Nothing
72 | k >= length (((cubes g) !! i) !! j) = Nothing
73 | otherwise = Just $ (((cubes g) !! i) !! j) !! k
76 -- | Takes a 'Grid', and returns all 'Cube's belonging to it that
77 -- contain the given 'Point'.
78 find_containing_cubes :: Grid -> Point -> [Cube]
79 find_containing_cubes g p =
80 filter contains_our_point all_cubes
82 all_cubes = flatten $ cubes g
83 contains_our_point = flip contains_point p