Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Error: Couldn't match expected type `Integer' against inferred type `Int'

I have a haskell function that that calculates the size of the list of finite Ints. I need the output type to be an Integer because the value will actually be larger than the maximum bound of Int (the result will be -1 to be exact if the output type is an Int)

size :: a -> Integer
size a =  (maxBound::Int) - (minBound::Int)

I understand the difference between Ints (bounded) and Integers (unbounded) but I'd like to make an Integer from an Int. I was wondering if there was a function like fromInteger, that will allow me to convert an Int to an Integer type.

like image 609
Fry Avatar asked Feb 20 '10 08:02

Fry


1 Answers

You'll need to convert the values to Integers, which can be done by the fromIntegral function (numeric casting for Haskell):

fromIntegral :: (Integral a, Num b) => a -> b

It converts any type in the Integral class to any type in the (larger) Num class. E.g.

fromIntegral (maxBound::Int) - fromIntegral (minBound::Int)

However, I would not really trust the approach you're taking -- it seems very fragile. The behaviour in the presence of types that admit wraparound is pretty suspect.

What do you really mean by: "the size of the list of finite Ints". What is the size in this sense, if it isn't the length of the list?

like image 144
Don Stewart Avatar answered Nov 03 '22 00:11

Don Stewart