Skip to content

Instantly share code, notes, and snippets.

@nessamurmur
Created June 27, 2015 20:51
Show Gist options
  • Save nessamurmur/4aa3df4f9fbf564f79b1 to your computer and use it in GitHub Desktop.
Save nessamurmur/4aa3df4f9fbf564f79b1 to your computer and use it in GitHub Desktop.
Couldn't match expected type ‘Int’ with actual type ‘a’
‘a’ is a rigid type variable bound by
the type signature for
splitWhen :: (a -> Bool) -> [a] -> ([a], [a])
at src/Data/List/Extras.hs:27:14
Relevant bindings include
n :: a (bound at src/Data/List/Extras.hs:29:23)
xs :: [a] (bound at src/Data/List/Extras.hs:28:13)
p :: a -> Bool (bound at src/Data/List/Extras.hs:28:11)
splitWhen :: (a -> Bool) -> [a] -> ([a], [a])
(bound at src/Data/List/Extras.hs:28:1)
In the first argument of ‘splitAt’, namely ‘n’
In the expression: splitAt n xs
import Data.List
splitWhen :: (a -> Bool) -> [a] -> ([a], [a])
splitWhen p xs = case find p xs of
Just n -> splitAt n xs
Nothing -> (xs, [])
@PiDelport
Copy link

You can diagnose the type error more interactively by leaving out the explicit type for splitWhen, and checking if it compiles. It turns out that it does; inspecting the working, inferred type with ghci shows:

splitWhen :: (Int -> Bool) -> [Int] -> ([Int], [Int])

This means that the a type is too general: something inside splitWhen must be constraining it to Int. Looking at the types of the functions called by splitWhen, the first argument of splitAt stands out:

find :: (a -> Bool) -> [a] -> Maybe a
splitAt :: Int -> [a] -> ([a], [a])

It must be an Int, which is being matched with the result of find, which in turn is matched with the input predicate and list.

Knowing this, the GHC error message should hopefully make a bit more sense. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment