Haskell将整数转换为Int? [英] Haskell Convert Integer to Int?
问题描述
是否可以将整数转换为Int?另一个方向是可能的:toInteger。我知道Integer能够存储更大的值,但有时需要一个对话来使用std-lib函数。我试过(n :: 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 std-lib functions. I tried ( n :: Int) and other code samples I found - but nothing works.
takeN :: Integer -> [a] -> [a]
takeN n l = take n l
推荐答案
使用 fromIntegral
。
takeN :: Integer -> [a] -> [a]
takeN n l = take (fromIntegral n) l
$ c> fromIntegral ::(Integral a,Num b)=> a - > b ,所以有时你需要一个额外的类型注释(例如(fromIntegral n :: Int)
),但通常编译器可以推断哪个类型
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.
在您的示例的特殊情况下,在 Data.List
中有 genericTake ::(Integral i)=> i - > [a] - > [a]
,它执行与相同的操作
,但使用更一般的类型。
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.
这篇关于Haskell将整数转换为Int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!