Zuletzt geändert: So, 23.04.2006

«K12/K13» Q.hs «PDF», «POD»



Download
{-# OPTIONS_GHC -fglasgow-exts #-}

module Q where

import Base
import Q_
import N  (N)
import Z

data Q = Frac Z N

instance Show Q where
  show a = "Q[" ++ (show . toRational $ a) ++ "]"

instance Eq Q where
  (==) = q_boolop2 (==)

instance Num Q where
  (+) = q_op2 (+)
  (-) = q_op2 (-)
  (*) = q_op2 (*)

  abs    = q_op1 abs
  negate = q_op1 negate
  signum = q_op1 signum

  fromInteger = q_2q . fromInteger

instance Real Q where
  toRational = toRational . q2q_

instance Fractional Q where
  (/) = q_op2 (/)
  fromRational = q_2q . fromRational

instance Ord Q where
  (<=) = q_boolop2 (<=)

q_op1 :: (Q_ -> Q_) -> Q -> Q
q_op1 f a = q_2q $ f (q2q_ a)

q_op2 :: (Q_ -> Q_ -> Q_) -> Q -> Q -> Q
q_op2 f a b = q_2q $ f (q2q_ a) (q2q_ b)

q_boolop2 :: (Q_ -> Q_ -> Bool) -> Q -> Q -> Bool
q_boolop2 f a b = f (q2q_ a) (q2q_ b)

q2q_ :: Q -> Q_
q2q_ (Q.Frac z n) = Q_.Frac z (Pos n)

q_2q :: Q_ -> Q
q_2q (Q_.Frac z (Pos n)) = Q.Frac z n
q_2q (Q_.Frac z (Neg n)) = Q.Frac (negate z) n
q_2q (Q_.Frac z Zero)    = error "Division by Q_[0]!"