一、實現分數的常用運算
module MyFraction where
import Test.QuickCheck
import Prelude hiding ((<*>))
type Fraction = (Integer, Integer)
ratplus :: Fraction -> Fraction -> Fraction
ratplus (a,b)(c,d)
|a==0 =(c,d)
|c==0 =(a,b)
|otherwise =(div (a*d+b*c) ga , div (b*d) ga )
where
ga=gcd (a*d+b*c)(b*d)
ratminus :: Fraction -> Fraction -> Fraction
ratminus (a,b)(c,d)=
(div (a*d-b*c) gb , div (b*d) gb )
where
gb=gcd (a*d-b*c)(b*d)
rattimes :: Fraction -> Fraction -> Fraction
rattimes (a,b)(c,d)
|a*c==0 =(0,1)
|otherwise =(div (a*c) gc , div (b*d) gc )
where
gc=gcd (a*c)(b*d)
ratdiv :: Fraction -> Fraction -> Fraction
ratdiv (a,b)(c,d)=
(div (a*d) gd , div (b*c) gd )
where
gd=gcd (a*d)(b*c)
ratfloor :: Fraction -> Integer
ratfloor (a,b)=
div a b
ratfloat :: Fraction -> Float
ratfloat (a,b)=
fromInteger a / fromInteger b
rateq :: Fraction -> Fraction -> Bool
rateq (a,b)(c,d)=
if ((a*d-b*c) == 0) then True else False
--↓定義新的運算符
(<+>) :: Fraction -> Fraction -> Fraction
(a,b) <+> (c,d) =
ratplus (a,b) (c,d)
(<->) :: Fraction -> Fraction -> Fraction
(a,b) <-> (c,d) =
ratminus (a,b) (c,d)
(<*>) :: Fraction -> Fraction -> Fraction
(a,b) <*> (c,d) =
rattimes (a,b) (c,d)
(>) :: Fraction -> Fraction -> Fraction
(a,b) > (c,d) =
ratdiv (a,b) (c,d)
(<==>) :: Fraction -> Fraction -> Bool
(a,b) <==> (c,d) =
rateq (a,b) (c,d)
--↑定義新的運算符
--↓四則運算函數的性質(交換律
prop_change :: Fraction -> Fraction -> Bool
prop_change (a,b) (c,d)
|b*d == 0 =True
|otherwise =ratplus(a,b)(c,d) == ratplus (c,d)(a,b) &&rattimes(a,b)(c,d) == rattimes (c,d)(a,b)
--↑四則運算函數的性質(交換律
--↓解決四則運算優先級問題
infixl 7 <*>,>
infixl 6 <+>,<->
infixl 5 <==>
--
二、計算平方根的Newton-Raphson公式
module NewtonRaphson where
--類型
squareroot2 :: Float -> Integer -> Float
squareroot :: Float -> Float -> Integer -> Float
sqrtSeq :: Float -> Float -> [Float]
squareroot' :: Float -> Float -> Float -> Float
square_root2 :: [Float] -> Float -> Float
--表達式(?)
squareroot2 x n =
if n<=0 then x else squareroot2 ((x+2/x)/2) (n-1)
squareroot r x n =
if n<=0 then x else squareroot r ((x+r/x)/2) (n-1)
sqrtSeq r x =
[squareroot r x y|y<- [1..]]
squareroot' r x e =
square_root2 (sqrtSeq r x) e
square_root2 (y:ys) e =
if ((head ys)-y<=e && y-(head ys)<=e) then y else square_root2 ys e