maros
maros

Reputation: 45

What can be the fault in this haskell code?

Friendly numbers

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.

Upvotes: 1

Views: 127

Answers (1)

Will Ness
Will Ness

Reputation: 71065

1==1 has type Bool.

[1==1] has type [Bool].

(&&) expects two arguments of type Bool. Instead it finds two arguments of type [Bool]. the two types are different. The program is thus rejected.

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]

The square brackets around your tests are wrong. They shouldn't be there.

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

Upvotes: 3

Related Questions