--Exercise 4.17
rangeProduct:: Int->Int -> Int
rangeProduct a b
| a > b = 1
| a == b = a
| otherwise = a* b * ( rangeProduct (a+1) (b-1))
fac :: Int -> Int
fac a = rangeProduct 1 a
--Exercise 4.16
data Month = January
| February
| March
| April
| May
| June
| July
| August
| September
| October
| November
| December
deriving(Eq,Show,Ord)
month2Season :: Month -> Season
month2Season month
| March <= month && month <= May= Spring
| June <= month && month <= August = Summer
| September <= month && month <= November = Automn
month2Season _ = Winter
--Exercise 4.15
data Season = Spring | Summer | Automn | Winter
data Temp = Cold | Hot deriving (Eq,Show,Ord)
getTemp :: Season -> Temp
getTemp Automn = Hot
getTemp Summer = Hot
getTemp _ = Cold
--Exercise 4.14
--Exercise 4.13
--Exercise 4.12
outcome :: Move -> Move -> Result
outcome Rock Scissors = Win
outcome Scissors Paper = Win
outcome Paper Rock = Win
outcome Rock Paper = Lose
outcome Scissors Rock = Lose
outcome Paper Scissors = Lose
outcome _ _ = Draw
--Exercise 4.11
data Result = Win | Lose | Draw
data Move = Rock | Paper | Scissors
--Exercise 4.10
--Exercise 4.10
--Exercise 4.9
--Exercise 4.8
triArea :: Float -> Float -> Float -> Float
triArea a b c
| possible = sqrt (s*(s-a)*(s-b)*(s-c))
| otherwise = 0.0
where
s = (a+b+c)/2
possible = maxInt < a+b+c - maxInt
where maxInt = max a $ max b c
--Exercise 4.7
--Exercise 4.6
--Exercise 4.5
--Exercise 4.4
howManyofFourEqual :: Int -> Int -> Int -> Int -> Int
howManyofFourEqual a b c d =myEqualCount all
where all = [a,b,c,d]
myEqualCount :: [Int] -> Int
myEqualCount [] = 0
myEqualCount t@(x:xs) = (myGroupCount $ mygroup x t) + (myEqualCount $ listRemoveItem x t)
listRemoveItem :: Int -> [Int] -> [Int]
listRemoveItem a [] = []
listRemoveItem a (x:xs)
| a == x = listRemoveItem a xs
| otherwise = x: listRemoveItem a xs
myGroupCount :: [Int]-> Int
myGroupCount [] = 0
myGroupCount xs
| length xs ==1 = 0
| otherwise = length xs
mygroup :: Int -> [Int] -> [Int]
mygroup _ [] = []
mygroup a (x:xs)
| a == x = x : mygroup a xs
| otherwise = mygroup a xs
--Exercise 4.3
howManyEqual :: Int -> Int -> Int -> Int
howManyEqual a b c
| myEqual a b && myEqual b c && myEqual a b = 3
| myEqual a b || myEqual b c || myEqual a b = 2
| otherwise =0
myEqual :: Int -> Int -> Bool
myEqual a b
| a == b = True
| otherwise = False
--Exercise 4.2
between :: Int -> Int -> Int -> Bool
between a b c
| weakAscendingOrder a b c && (a /= b) && b /= c = True
| otherwise = False
weakAscendingOrder :: Int -> Int -> Int -> Bool
weakAscendingOrder a b c
| a <=b && b <=c = True
| otherwise = False
--Exercise 4.1
maxFour :: Int -> Int -> Int -> Int -> Int
maxFour a b c d = max a $ maxThree b c d
maxThree :: Int -> Int ->Int -> Int
maxThree a b c = max a $ max b c
--Exercise 3.27
--Exercise 3.26
mymax :: Int -> Int -> Int
mymax a b
| a > b = a
| otherwise = b
Haskell函数式编程基础习题(2)
最新推荐文章于 2021-07-27 11:46:44 发布