Fibonacci.hs 1.6 KB
Newer Older
1 2 3 4 5 6 7 8 9
{-|
Module      : Gargantext.Prelude.Utils
Description : Useful Tools near Prelude of the project
Copyright   : (c) CNRS, 2017-Present
License     : AGPL + CECILL v3
Maintainer  : team@gargantext.org
Stability   : experimental
Portability : POSIX

Alexandre Delanoë's avatar
Alexandre Delanoë committed
10
Nice optimization of the Fibonacci function.
11

Alexandre Delanoë's avatar
Alexandre Delanoë committed
12
Source:
13 14 15 16 17 18 19 20 21 22 23 24
Gabriel Gonzales, Blazing fast Fibonacci numbers using Monoids, 2020-04,
http://www.haskellforall.com/2020/04/blazing-fast-fibonacci-numbers-using.html
(This post illustrates a nifty application of Haskell’s standard library to solve a numeric problem.)

TODO: quikcheck

-}



module Gargantext.Prelude.Fibonacci where

25 26 27
import Protolude

import qualified Data.Monoid as Monoid
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
import qualified Data.Semigroup as Semigroup

-------------------------------------------------------------
fib' :: Integer -> Integer
fib' 0 = 0
fib' 1 = 1
fib' n = fib (n-1) + fib (n-2)
-------------------------------------------------------------


data Matrix2x2 = Matrix
    { x00 :: Integer, x01 :: Integer
    , x10 :: Integer, x11 :: Integer
    }

43
instance Monoid.Monoid Matrix2x2 where
44 45 46 47 48 49
    mempty =
        Matrix
            { x00 = 1, x01 = 0
            , x10 = 0, x11 = 1
            }

50
instance Semigroup.Semigroup Matrix2x2 where
51 52 53 54 55 56 57 58 59 60 61 62 63 64
    Matrix l00 l01 l10 l11 <> Matrix r00 r01 r10 r11 =
        Matrix
            { x00 = l00 * r00 + l01 * r10, x01 = l00 * r01 + l01 * r11
            , x10 = l10 * r00 + l11 * r10, x11 = l10 * r01 + l11 * r11
            }

fib :: Integer -> Integer
fib n = x01 (Semigroup.mtimesDefault n matrix)
  where
    matrix =
        Matrix
            { x00 = 0, x01 = 1
            , x10 = 1, x11 = 1
            }