Search code examples
listhaskellfunctional-programming

Is there anyway to get how long the list is in Haskell without using the length function in this situation?


I have to define a function according to this signature:

indexList :: [a] -> [(Int, a)]

The function is supposed to unzip the list elements into a tuple - the first part of the tuple being how far is the tuple from the end of the list - and the second part being the original element itself. (Must be recursive, and I can't use the length function).

expecting this test to be true:

indexList [True, False, True] == [(2, True), (1, False), (0, True)]

I have gotten here so far:

indexList [] = []
indexList (x : xs) = ({-HowFarIsIt-}, x) : indexList xs

Solution

  • You can look at the result of the next tuple of the result, so:

    indexList :: [a] -> [(Int, a)]
    indexList [] = []
    indexList [x] = [(0, x)]
    indexList (x : xs) = … : ys
        where ys@((i,_):_) = indexList xs

    where I leave filling in as an exercise.

    You can also work with a helper function to enable total pattern matching:

    import Data.List.NonEmpty(NonEmpty((:|)), (<|))
    
    indexList :: [a] -> [(Int, a)]
    indexList [] = []
    indexList (x : xs) = let (x :| xs) = indexList' x xs in x : xs
    
    indexList' :: a -> [a] -> NonEmpty [(a, Int)]
    indexList' x [] = (0, x) :| []
    indexList' x xs = … <| ys
        where ys@((i,_) :| _) = indexList' x xs