Haskell - find an item in a list and return its position

So, I need to make a function described as

invFib :: Integer -> Maybe Integer

which takes an integer and looks for it in a fibonacci sequence (as described below)

fibs :: [Integer]
fibs = 0:1:(zipWith (+) fibs (tail fibs)) 

and returns the index of the example number:

invFib 0 ~> Just 0

invFib 1~> Just 1orJust 2

map invFib [54, 55, 56] ~> [Nothing,Just 10,Nothing]

invFib (fibs !! 99) ~> Just 99

I tried to make a function that takes a list of integers and splashes out the index, but it continues to fail. Any thoughts?

this is the function i tried -

findNum :: [Integer] -> Integer -> Integer -> Integer
findNum x:xs y z = if x == y
                then z
                else findNum xs y (z+1)

Edit: the function hangs on numbers that are not in the fibonacci sequence, it also shows only 1 value when entering 1

invFib :: Integer -> Maybe Integer
invFib n = if n < 0
        then Nothing
        else fmap fromIntegral (elemIndex n fibs)
+5
source share
3 answers

, , fibs , . , , , 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

:

$ 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]

. zip fibs [0..], dropWhile n , .

+8

"takeWhile", "fibs", ? ​​, "elemIndex", , .

elemIndex myInteger (takeWhile (<= myInteger) fibs)
+7

If you have already calculated fibs, then the answer is simple:

import Data.List

invFib :: Integer -> Maybe Integer
invFib n = fmap fromIntegral (elemIndex n fibs)

fibs :: [Integer]
fibs = 0:1:(zipWith (+) fibs (tail fibs))
+1
source

All Articles