Tony Mak
Tony Mak

Reputation: 21

Couldn't match expected type `Bool' with actual type `[[Integer]]

I'm new to Haskell and have a question about types, it error out because it couldn't match expected type. I believe squarePrime is a bool, correct me if i'm wrong and it is complaining because it wants a int? Can someone explain, thanks in advance.

squarePrimes n =  [n^2 | (n) <- [2..n-1], (all (\a -> mod n a /= 0) [2..n-1])]
multiOfFive a = mod a 5 == 0 

fun n = [n | n <-[1..n], multiOfFive || squarePrimes n]

Upvotes: 1

Views: 311

Answers (2)

sshine
sshine

Reputation: 16105

I believe squarePrimes is a Bool, correct me if I'm wrong

GHCi will tell you:

λ> let squarePrimes n = [n^2 | (n) <- [2..n-1], (all (\a -> mod n a /= 0) [2..n-1])]
λ> :t squarePrimes 
squarePrimes :: Integral a => a -> [a]

It is complaining because it wants an int? Can someone explain

Here Integral i => i is any integer type. That could for example be Int or Integer. This is because the integer literals 0, 1, 2 and the arithmetic operators you use aren't restricted to a specific integer type.

You're using squarePrimes n as a Bool.

You're also using multiOfFive as a Bool when its type is:

λ> let multiOfFive a = mod a 5 == 0 
λ> :t multiOfFive 
multiOfFive :: Integral a => a -> Bool

so a function that takes an integer type and returns a Bool.

Upvotes: 2

user12701374
user12701374

Reputation:

The 'squarePrimes n' function returns a list of Integers, as opposed to a Bool or a list of Bools. Looking at the list comprehension:

[n^2 | (n) <- [2..n-1], (all (\a -> mod n a /= 0) [2..n-1])]

This will produce a list of n^2, of n pulled from the range [2..n-1], for every n that satisfies the condition:

(all (\a -> mod n a /= 0) [2..n-1])

Then, in the list comprehension used in the definition of 'fun':

[n | n <-[1..n], multiOfFive || squarePrimes n]

A list is being constructed of each n in the range 1 to n, as long as the following condition is true:

multiOfFive || squarePrimes n

Haskell is expecting this to evaluate to a Bool. However, 'multiOfFive' is being called without any argument, and 'squarePrimes n' returns a list of Integers, as opposed to a Bool.

Without knowing exactly what the intention of 'fun n' is, I have altered the provided code a little bit to get a list comprehension that loads without error:

fun n = [n | n <- [1..n], (multiOfFive n) || (elem n (squarePrimes n))]

Now, it uses the 'elem' function to check whether a given 'n' is an element of the list 'squarePrimes n'.

Upvotes: 4

Related Questions