Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import Prelude
- data Quaternion = Quat { a :: Double,
- b :: Double,
- c :: Double,
- d :: Double }
- deriving Eq
- -- Take the real part of a quaternion (used for testing)
- -- realPart (a + b*i + c*j + d*k) == a
- realPart :: Quaternion -> Double
- realPart q = (a q)
- i, j, k, zeroQuat :: Quaternion
- i = Quat 0 1 0 0
- j = Quat 0 0 1 0
- k = Quat 0 0 0 1
- zeroQuat = Quat 0 0 0 0
- fromDouble :: Double -> Quaternion
- fromDouble x = Quat x 0 0 0
- instance Show Quaternion where
- show (Quat a b c d) = show a ++ " + " ++ show b ++ "i + " ++ show c ++ "j + " ++ show d ++ "k"
- instance Num Quaternion where
- q1 + q2 = Quat (a q1 + a q2) (b q1 + b q2) (c q1 + c q2) (d q1 + d q2)
- q1 * q2 = Quat a_term b_term c_term d_term
- where
- a_term = a q1 * a q2 - b q1 * b q2 - c q1 * c q2 - d q1 * d q2
- b_term = a q1 * b q2 + b q1 * a q2 + c q1 * d q2 - d q1 * c q2
- c_term = a q1 * c q2 - b q1 * d q2 + c q1 * a q2 + d q1 * b q2
- d_term = a q1 * d q2 + b q1 * c q2 - c q1 * b q2 + d q1 * a q2
- abs q = fromDouble (sqrt (sum_prod))
- where
- sum_prod = a q * a q + b q * b q + c q * c q + d q * d q
- -- Divide each Double component by the (abs x)
- signum q =
- if q /= zeroQuat then
- Quat (a q / absVal) (b q / absVal) (c q / absVal) (d q / absVal)
- else
- zeroQuat
- where
- absVal = realPart (abs q)
- negate q = Quat (- a q) (- b q) (- c q) (-d q)
- fromInteger n = Quat (fromIntegral n) 0 0 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement