chainQuery :: (Enum a, Integral a, Ord b) => a -> b -> [c]
chainQuery n min = map length $ filter beatingLength $ map chain [1..n]
where
beatingLength :: [a] -> Bool
beatingLength xs = length xs > min
chain :: (Integral a) => a -> [a]
chain n
| n <= 1 = [n]
| even n = n:(chain $ div n 2)
| otherwise = n:(chain $ n * 3 + 1)
-
In the code sample above why isn’t GHC able to deduce that ‘c’ is an Int by looking at the type definition for length?
-
Why does GHC need to know anything about ‘b’ other than that it is an Ord?
-
Is there a better way to write this function?
GHC is able to infer
[Int]as the result type for the function. The problem is that you’ve claimed in your type signature that it should be more polymorphic, that the result could be a list of any type, which does not make sense since the return value comes from themap lengthso it must have type[Int]. This is what GHC is complaining about when it saysCould not deduce (c ~ Int).You’re comparing
mintolength xs. The greater-than operator has the type(>) :: (Ord a) => a -> a -> Bool, which means that both sides must be the same type. The type oflength xsisInt, so this forcesminto beIntas well.Probably. For example, you can map the length before doing the filtering. This makes it easy to use an operator section instead of your
beatingLengthfunction. You can also move the parenthesis to save a use of$to make the code a bit neater.For reference, the easiest way to solve a problem like this is to remove your type signature and see what type was inferred in GHCi using the
:tcommand. In this case, the inferred type is