Inspired by this post, I wrote a fibonacci implementation using hmatrix
{-# language OverloadedLists #-}
import Numeric.LinearAlgebra
import Data.Semigroup (stimes)
-- can't use stimesMonoid to eliminate 0 case, because matrix mempty has the wrong dimension (1><1)
fib :: Int -> Int
fib 0 = 0
fib n = fromIntegral x
where
[x, _] = stimes n fibMatrix #> [0, 1]
fibMatrix :: Matrix Z
fibMatrix = (2><2) [1, 1, 1, 0]
main = do
mapM_ print $ takeWhile (>=0) $ map fib [0..]
Unfortunately, it doesn’t get very far into the sequence before overflowing the size of an Int64
(that’s what Z
is an alias for). Unfortunately I can’t use Integer
- it seems that hmatrix
only supports Storable
elements. I guess this is because hmatrix
is a wrapper over fast c libraries.
So, my questions:
- Long shot, but is there a way to get around this issue without switching libraries? I like
hmatrix
's API a lot. - If not, what library would you recommend that can handle arbitrary precision integers?