-{-# LANGUAGE TypeSynonymInstances #-}
+{-# LANGUAGE FlexibleInstances #-}
-module Point
+module Point (
+ Point(..),
+ dot,
+ scale )
where
-import Comparisons
+import Test.Tasty.QuickCheck ( Arbitrary(..) )
-type Point = (Double, Double, Double)
+-- | Represents a point in three dimensions. We use a custom type (as
+-- opposed to a 3-tuple) so that we can make the coordinates strict.
+--
+data Point =
+ Point !Double !Double !Double
+ deriving (Eq, Show)
-x_coord :: Point -> Double
-x_coord (x, _, _) = x
-y_coord :: Point -> Double
-y_coord (_, y, _) = y
+instance Arbitrary Point where
+ arbitrary = do
+ (x,y,z) <- arbitrary
+ return $ Point x y z
-z_coord :: Point -> Double
-z_coord (_, _, z) = z
instance Num Point where
- (x1,y1,z1) + (x2,y2,z2) = (x1+x2, y1+y2, z1+z2)
- (x1,y1,z1) - (x2,y2,z2) = (x1-x2, y1-y2, z1-z2)
- (x1,y1,z1) * (x2,y2,z2) = (x1*x2, y1*y2, z1*z2)
- abs (x, y, z) = (abs x, abs y, abs z)
- signum (x, y, z) = (signum x, signum y, signum z)
- fromInteger n = (fromInteger n, fromInteger n, fromInteger n)
+ (Point x1 y1 z1) + (Point x2 y2 z2) = Point (x1+x2) (y1+y2) (z1+z2)
+ (Point x1 y1 z1) - (Point x2 y2 z2) = Point (x1-x2) (y1-y2) (z1-z2)
+ (Point x1 y1 z1) * (Point x2 y2 z2) = Point (x1*x2) (y1*y2) (z1*z2)
+ abs (Point x y z) = Point (abs x) (abs y) (abs z)
+ signum (Point x y z) = Point (signum x) (signum y) (signum z)
+ fromInteger n =
+ Point coord coord coord
+ where
+ coord = fromInteger n :: Double
-- | Scale a point by a constant.
scale :: Point -> Double -> Point
-scale (x, y, z) d = (x*d, y*d, z*d)
+scale (Point x y z) d = Point (x*d) (y*d) (z*d)
--- | Returns the distance between p1 and p2.
-distance :: Point -> Point -> Double
-distance p1 p2 =
- sqrt $ (x2 - x1)^(2::Int) + (y2 - y1)^(2::Int) + (z2 - z1)^(2::Int)
- where
- x1 = x_coord p1
- x2 = x_coord p2
- y1 = y_coord p1
- y2 = y_coord p2
- z1 = z_coord p1
- z2 = z_coord p2
-
-
--- | Returns 'True' if p1 is close to (within 'epsilon' of) p2,
--- 'False' otherwise.
-is_close :: Point -> Point -> Bool
-is_close p1 p2 = (distance p1 p2) ~= 0
+-- | Returns the dot product of two points (taken as three-vectors).
+{-# INLINE dot #-}
+dot :: Point -> Point -> Double
+dot (Point x1 y1 z1) (Point x2 y2 z2) =
+ (x2 - x1)^(2::Int) + (y2 - y1)^(2::Int) + (z2 - z1)^(2::Int)