友好號碼
一個數的除數之和小于它自己的數與另一個數相等,反之亦然的一對數,我們稱之為友好數。一個例子是數字對 (220; 284)。
220:較小的除數:1 2 4 5 10 11 20 22 44 55 110 = 284
284:較小的除數:1 2 4 71 142 = 220
輸入
areAmicableNumbers函式,它決定一對數字是否為友好數字!以下每個測驗用例都必須給出
True:areAmicableNumbers 220 284 == Truenot (areAmicableNumbers 220 283) == TrueareAmicableNumbers 1184 1210 == True
areAmicableNumbers :: Integral a => a -> a -> [Bool]
areAmicableNumbers x y =
[(sum [k | k <- [1..x], x `mod` k ==0]) == y]
&&
[(sum [i | i <- [1..y], y `mod` i ==0]) == x]
Error: Homework1.hs:23:26: error:
* Couldn't match expected type `Bool' with actual type `[Bool]'
* In the first argument of `(&&)', namely
`[(sum [k | k <- [1 .. x], x `mod` k == 0]) == y]'
In the expression:
[(sum [k | k <- [1 .. x], x `mod` k == 0]) == y]
&& [(sum [i | i <- [1 .. y], y `mod` i == 0]) == x]
In an equation for `areAmicableNumbers':
areAmicableNumbers x y
= [(sum [k | k <- [1 .. x], x `mod` k == 0]) == y]
&& [(sum [i | i <- [1 .. y], y `mod` i == 0]) == x]
|
23 | areAmicableNumbers x y = [(sum [k | k <- [1..x], x `mod` k ==0]) == y] && [(sum [i | i <- [1..y], y `mod` i ==0]) == x]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Homework1.hs:23:75: error:
* Couldn't match expected type `Bool' with actual type `[Bool]'
* In the second argument of `(&&)', namely
`[(sum [i | i <- [1 .. y], y `mod` i == 0]) == x]'
In the expression:
[(sum [k | k <- [1 .. x], x `mod` k == 0]) == y]
&& [(sum [i | i <- [1 .. y], y `mod` i == 0]) == x]
In an equation for `areAmicableNumbers':
areAmicableNumbers x y
= [(sum [k | k <- [1 .. x], x `mod` k == 0]) == y]
&& [(sum [i | i <- [1 .. y], y `mod` i == 0]) == x]
|
23 | areAmicableNumbers x y = [(sum [k | k <- [1..x], x `mod` k ==0]) == y] && [(sum [i | i <- [1..y], y `mod` i ==0]) == x]
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Failed, no modules loaded.
uj5u.com熱心網友回復:
1==1有型別Bool。
[1==1]有型別[Bool]。
(&&)需要兩個型別的引數Bool。相反,它會找到兩個型別為 的引數[Bool]。這兩種型別是不同的。程式因此被拒絕。
GHCi> :type (&&)
(&&) :: Bool -> Bool -> Bool
> :type (&&) :: [Bool] -> [Bool] -> [Bool]
<interactive>:1:1:
Couldn't match type `Bool' with `[Bool]'
Expected type: [Bool] -> [Bool] -> [Bool]
Actual type: Bool -> Bool -> Bool
In the expression: (&&) :: [Bool] -> [Bool] -> [Bool]
測驗周圍的方括號是錯誤的。他們不應該在那里。
GHCi> :type [1==1] :: Bool
<interactive>:1:1:
Couldn't match expected type `Bool' with actual type `[Bool]'
In the expression: [1 == 1] :: Bool
GHCi> :type (1==1)
(1==1) :: Bool
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/316838.html
