So the key here is that fibs
is infinite, but also monotonically increasing. Hence, once it exceeds the number being looked for, it can return Nothing
:
findIndexInAscendingList :: (Ord a) => a -> [a] -> Maybe Integer
findIndexInAscendingList a xs = find 0 xs
where
find i [] = Nothing -- won't get used for fibs
find i (x:xs) | a == x = Just i
| a < x = Nothing
| otherwise = find (i + 1) xs
invFib :: Integer -> Maybe Integer
invFib n = findIndexInAscendingList n fibs
And so:
$ ghci
GHCi, version 7.4.2: http://www.haskell.org/ghc/ :? for help
λ: :load Fib.hs
[1 of 1] Compiling Main ( Fib.hs, interpreted )
Ok, modules loaded: Main.
λ: map invFib [54,55,56]
[Nothing,Just 10,Nothing]
There are some other ways to do it too. Think about zip fibs [0..]
and then you could use dropWhile
to remove the portion less than n
and test what's left.