27 June, 2006

[Haskell] Exercise 3.6 - 3.9

●Excercise 3.6

mystery :: Int -> Int -> Int -> Bool
mystery m n p = not ((m == n) && (n==p))

Main> mystery 1 1 1
False
Main> mystery 1 1 2
True
Main> mystery 1 2 1
True
Main> mystery 2 1 1
True
Main> mystery 1 2 3
True
Main>

m, n, p が等しい場合だけFalseで他はTrue。

● Exercise 3.7

threeDifferent :: Int -> Int -> Int -> Bool
threeDifferent m n p = (m /= n) && (n /= p) && (p /= m)

Main> threeDifferent 1 2 3
True
Main> threeDifferent 1 2 1
False
Main> threeDifferent 1 1 2
False
Main> threeDifferent 2 1 1
False
Main> threeDifferent 1 1 1
False
Main> threeDifferent 3 4 3
False

threeDifferent 3 4 3
= (3 /= 4) && (4 /= 3) && (3 /= 3)
= True && (4 /= 3) && (3 /= 3)
= (4 /= 3) && (3 /= 3)
= True && (3 /= 3)
= (3 /= 3)
= False

●Exercise 3.8
threeEqualsを真似て。

fourEqual :: Int -> Int -> Int -> Int -> Bool
fourEqual m n p q = (m==n) && (n==p) && (p==q)

threeEqualsを用いて。

threeEquals :: Int -> Int -> Int -> Bool
threeEquals m n p = (m==n) && (n==p)

fourEquals :: Int -> Int -> Int -> Int -> Bool
fourEquals m n p q = (threeEquals m n p) && (p==q)


●Exercise 3.9
評価する箇所をイタリックで書くと、
threeEquals (2+3) 5 (11 `div` 2)
= ((2+3) == 5) && (5 == (11 `div` 2)) && ((11 `div` 2) == (2+3))
= (5 == 5) && (5 == (11 `div` 2)) && ((11 `div` 2) == 5)
= True && (5 == (11 `div` 2)) && ((11 `div` 2) == 5)
= (5 == (11 `div` 2)) && ((11 `div` 2) == 5)
= (5 == 5) && (5 == 5)
= True && (5==5)
= (5==5)
= True
のような感じか。他は省略。

Main> threeEquals (2+3) 5 (11 `div` 2)
True
Main> mystery (2+3) 5 (11 `div` 2)
False
Main> threeDifferent (2+3) 5 (11 `div` 2)
False
Main> fourEqual (2+3) 5 (11 `div` 2) (21 `mod` 11)
False

No comments: