04 July, 2006

[Haskell] Exercise 5.1 - 5.4

○ Exercise 5.1
tuple の使い方を学ぶ

maxOccurs :: Int -> Int -> (Int,Int)
maxOccurs x y
| x == y = (x, 2)
| x > y = (x, 1)
| x < y = (y, 1)

Main> maxOccurs 3 5
(5,1)
Main> maxOccurs 5 3
(5,1)
Main> maxOccurs 5 5
(5,2)

maxThreeOccurs :: Int -> Int -> Int -> (Int,Int)
maxThreeOccurs x y z
| m == z = (m, n+1)
| m > z = (m, n)
| m < z = (z, 1)
where m = fst $ maxOccurs x y
n = snd $ maxOccurs x y

Main> maxThreeOccurs 3 4 5
(5,1)
Main> maxThreeOccurs 3 5 4
(5,1)
Main> maxThreeOccurs 4 3 5
(5,1)
Main> maxThreeOccurs 4 5 3
(5,1)
Main> maxThreeOccurs 5 3 4
(5,1)
Main> maxThreeOccurs 5 4 3
(5,1)
Main> maxThreeOccurs 3 4 4
(4,2)
Main> maxThreeOccurs 4 3 4
(4,2)
Main> maxThreeOccurs 4 4 3
(4,2)
Main> maxThreeOccurs 4 4 4
(4,3)
Main>

○ Exercise 5.2
listをsortすれば終わりのような問題ではあるが、tupleを扱う練習なので素直に。

maxThree, middleThree, minThree :: (Int, Int, Int) -> Int
maxThree (x, y, z)
| x >= y && x >= z = x
| y >= x && y >= z = y
| otherwise = z

minThree (x, y, z)
| x <= y && x <= z = x
| y <= x && y <= z = y
| otherwise = z

middleThree (x, y, z) = x + y + z - maxThree (x,y,z) - minThree (x,y,z)

orderTriple :: (Int, Int, Int) -> (Int, Int, Int)
orderTriple (x,y,z) = (minThree (x,y,z), middleThree (x,y,z), maxThree (x,y,z))


Main> orderTriple (1,2,3)
(1,2,3)
Main> orderTriple (1,3,2)
(1,2,3)
Main> orderTriple (2,1,3)
(1,2,3)
Main> orderTriple (2,3,1)
(1,2,3)
Main> orderTriple (3,1,2)
(1,2,3)
Main> orderTriple (3,2,1)
(1,2,3)
Main> orderTriple (1,1,2)
(1,1,2)
Main> orderTriple (1,2,1)
(1,1,2)
Main> orderTriple (2,1,1)
(1,1,2)
Main> orderTriple (1,1,1)
(1,1,1)
Main>

○ Exercise 5.3, 5.4
直線 ax+by+c=0 がx軸と交わる点は、x=-c/a if a /= 0。
a /= 0 --> (-c/a, True)を、a == 0 --> (0.0, false) を返す関数を作る事にする。

-- find x for ax+by+c=0 where y=0
-- x = -c/a
findX :: (Float, Float, Float) -> (Float, Bool)
findX (a, b, c)
| a /= 0.0 = ((-c) / a, True)
| a == 0.0 = (0.0, False)

Main> findX (1.0, 1.0, 1.0)
(-1.0,True)
Main> findX (1.0, 0.0, 1.0)
(-1.0,True)
Main> findX (0.0, 0.0, 1.0)
(0.0,False)
Main> findX (0.0, 1.0, 1.0)
(0.0,False)
Main> findX (1.0, 2.0, 3.0)
(-3.0,True)
Main>

1 comment:

Anonymous said...

Try input 5 1 1 in your solution for 5.1 :P