如何实施!! Haskell 中的整数?

How to implement !! for Integer in Haskell?

我是 Haskell 编程新手。我正在寻找 !! 运算符的实现,我需要使用它而不是 [a] -> Int -> a[a] -> Int -> [a] 但作为 [a] -> Integer -> [a][a] -> Integer -> a.

一些我想用到的代码:

next x = 1: zipWith (+) x (tail x) ++ [1]
bins :: Integer -> [Integer]
bins n
  | n < 0 = undefined
  | otherwise = (( (foldr (:) [] $ unfoldr (\st->Just(st,next st)) [1]) !! n ))

而且我不能只将 bins :: Integer -> [Integer] 的类型更改为 bins :: Int -> [Integer] 因为这是测试中的严格条件。

您可以像这样通过 fromIntegral :: (Num b, Integral a) => a -> b 调用它:

  ..... !! (fromIntegral n)

并保持你的类型签名不变,因为 Integer 是一个 Integral 类型而 Int 是一个 Num.

在 GHCi 中,

> fromIntegral (1::Integer)::Int
1
it :: Int

> :i Integral
class (Real a, Enum a) => Integral a where
 ....
instance Integral Integer -- Defined in `GHC.Real'
instance Integral Int -- Defined in `GHC.Real'

> :i Num
class Num a where
 ....
instance Num Integer -- Defined in `GHC.Num'
instance Num Int -- Defined in `GHC.Num'
....

当然这会引入常见的整数回绕问题,

> maxBound :: Int
9223372036854775807
it :: Int

> (maxBound :: Int) + 1
-9223372036854775808
it :: Int

> (fromIntegral (maxBound :: Int) :: Integer) + 1
9223372036854775808
it :: Integer

> (fromIntegral (fromIntegral (maxBound :: Int) :: Integer) + 1) :: Int
-9223372036854775808

但可以可能 安全地假设您实际上不会使用如此高的索引值,永远