· haskell

Haskell: Couldn't match expected type `Int' with actual type `Integer'

One of the most frequent compilation error messages that I’ve been getting while working through the Project Euler problems in Haskell is the following:

Couldn't match expected type `Int' with actual type `Integer'

In problem 11, for example, I define the grid of numbers like so:

grid = [[08,02,22,97,38,15,00,40,00,75,04,05,07,78,52,12,50,77,91,08],

Which has the following type:

> :t grid
grid :: [[Integer]]

The problem is that I wrote some functions to pass the grid to which expect it to be an array of array of Ints. For example the following function helps find the diagonals left to right from our current position:

-- implementation of findValue and hasItem isn't relevant here...

diagonalAt :: Int -> Int -> [[Int]] -> [Int]
diagonalAt x y grid = [findValue x y grid z | z <- [0..(length grid)], 
						hasItem grid (x + z), 
						hasItem (grid !! (x + z)) (y + z)]

> diagonalAt 0 0 grid
    Couldn't match expected type `Int' with actual type `Integer'
    Expected type: [[Int]]
      Actual type: [[Integer]]
    In the third argument of `diagonalAt', namely `x'
    In the expression: diagonalAt 0 0 x

But if we give a type definition instead of allowing it to be inferred…

grid :: [[Int]]
-- definition of grid as before

…then it will be of the type we want:

> :t grid
grid :: [[Int]]

Alternatively we can make use of the fromIntegral function to convert from Integer to Int which in this situation leads to the following code:

> diagonalAt 0 0 (map (map fromIntegral) grid)
  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket