Haskell Convert Integer to Int?

51,379

Solution 1

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.

Solution 2

there is also fromInteger (fromIntegral is just fromInteger . toInteger, but since you have an Integer anyway so you can skip the second part)

Share:
51,379

Related videos on Youtube

NaN
Author by

NaN

student@Vienna University of Technology justrocketscience.com

Updated on November 24, 2021

Comments

  • NaN
    NaN over 2 years

    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