How to use fromInteger in Haskell?

One way to calculate 2 ^ 8 in haskell is to write

product(replicate 8 2) 

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

 power1 :: Integer β†’ Integer β†’ Integer power1 nk | k < 0 = error errorText power1 n 0 = 1 power1 nk = product(replicate kn) 

I get the following error:

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

I guess I should use the fromInteger function somewhere ... I just don't know where and how? Is this an interface or what is from Integer, and how to use it?

thanks

+4
source share
3 answers

First, never use fromInteger. Use fromIntegral.

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

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

so when you pass "k" as the argument you are asserting is Integer with a 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 nk = product (genericReplicate kn) 
+11
source

Perhaps a simpler solution is to define a function type definition:

 power1 :: Integer -> Int -> Integer 
+2
source

You should also look at the rest of the error message, it will definitely tell you 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 kn)' In the expression: product (replicate kn) 

"In the first replication argument." This is the place to add fromIntegral .

+1
source

All Articles