Find max element and index of a list in Haskell
It's because of a slight bug in your code. You have:
where (t, ti) = pmaxim xs (ti + 1)
... but it should actually be:
where (t, ti) = pmaxim xs (xi + 1)
This fixes your code, which now produces the correct solution:
>>> maxim [1, 2, 3, 2, 1]
(3, 2)
Your code hanged because your computation for ti
results in an endless loop since you accidentally defined it in terms of itself. Note that ghc
is a sufficiently smart compiler and figures out that t
does not depend on the value of ti
, which is why your version could still successfully compute the maximum value even if it cannot compute the index.
The standard way to debug pure computations is the Debug.Trace
module.
As a side note, there is a much simpler solution:
import Data.List
import Data.Ord
maxi xs = maximumBy (comparing fst) (zip xs [0..])
Edit: Oops, I didn't see that you were deliberately implementing it from scratch, but I'll still leave that there.