Daemon
Daemon

Reputation: 13

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

Upvotes: 1

Views: 202

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

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

Upvotes: 2

Related Questions