Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use fromInteger in Haskell?

Tags:

haskell

ghc

ghci

One way to calculate 2^8 in haskell is by writing

product(replicate 8 2)

When trying to create a function for this, defined as follows...

power1 :: Integer →  Integer → Integer
power1 n k | k < 0 = error errorText
power1 n 0 = 1
power1 n k = product(replicate k n)

i get the following error:

Couldn't match expected type 'Int' against inferred type 'Integer'

My guess is that I must use the fromInteger function somewhere... I'm just not sure where or how? Is it an interface or what is fromInteger, and how should I use it?

Thanks

like image 463
Mickel Avatar asked Nov 02 '09 19:11

Mickel


People also ask

What does fromInteger do in Haskell?

Conversion from an Integer. An integer literal represents the application of the function fromInteger to the appropriate value of type Integer, so such literals have type. Convert from integer to ring.

What does integral mean in Haskell?

Haskell has two integral types, namely Int and Integer . Int is the type of limited-precision integers; this means that there is a smallest integer of type Int , namely minBound , and a greatest integer of type Int , namely maxBound .


3 Answers

Firstly, never use fromInteger. Use fromIntegral.

You can see where the type error is by looking at the type of replicate:

replicate :: Int -> a -> [a]

so when you giv it 'k' as an argument, which you've asserted is an Integer via the type declaration, we have a type error.

A better approach for this would be to use genericReplicate:

genericReplicate :: (Integral i) => i -> a -> [a]

So then:

power1 n k = product (genericReplicate k n)
like image 124
Don Stewart Avatar answered Oct 27 '22 06:10

Don Stewart


You should look at the rest of the error message as well, it tells you exactly the answer to your question:

Couldnt match expected type 'Int' against inferred type 'Integer'
In the first argument of 'replicate', namely 'k'
In the first argument of 'product', namely '(replicate k n)'
In the expression: product (replicate k n)

"In the first argument of replicate". That's the place to add the fromIntegral.

like image 39
yairchu Avatar answered Oct 27 '22 05:10

yairchu


Maybe a simpler solution is to change the function's type definition to:

power1 :: Integer -> Int -> Integer
like image 22
Jacob Avatar answered Oct 27 '22 06:10

Jacob