Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Convert Integer to Int?

Is it possible to cast an Integer to an Int? The other direction is possible: toInteger. I know that Integer is able to store bigger values, but sometimes a conversation is needed to use functions in the standard library. I tried (n :: Int) and other code samples I found - but nothing works.

takeN :: Integer -> [a] -> [a] takeN n l = take n l 
like image 772
NaN Avatar asked Nov 01 '11 09:11

NaN


People also ask

Can integer be converted to int?

To convert the Integer to int, we can use the intValue() or the parseInt() method.

How do you convert a number to an integer in Haskell?

fromInteger :: Num a => Integer -> a. as well as for converting to Integer s: toInteger:: Integral a => a -> Integer.

What does int -> int mean Haskell?

It states that this function is of type Int -> Int , that is to say, it takes an integer as its argument and it returns an integer as its value.

What is the difference between int and Integer in Haskell?

What's the difference between Integer and Int ? Integer can represent arbitrarily large integers, up to using all of the storage on your machine. Int can only represent integers in a finite range.


1 Answers

Use fromIntegral.

takeN :: Integer -> [a] -> [a] takeN n l = take (fromIntegral n) l 

Note that fromIntegral :: (Integral a, Num b) => a -> b, so sometimes you will need an extra type annotation (e.g. (fromIntegral n :: Int)), but usually the compiler can infer which type you want.

In the special case of your example, in Data.List there is genericTake :: (Integral i) => i -> [a] -> [a], which does the same thing as take but with a more general type.

like image 79
dave4420 Avatar answered Oct 05 '22 17:10

dave4420