I'm learning Haskell and I'm trying to translate a pseudocode algorithm to generate the next permutation from a previous permutation.

A permutation is a list of n numbers (let's call it a) in {1 .. n} appearing once in arbitrary order.

The first step is to find the largest index j in the list for which a[j] < a[j+1].

The pseudocode is simple:

j:= n-1

while a[j] > a[j+1]
    j:=j-1


I've coded a haskell function to do this, but it is much uglier than the pseudocode :

j :: Integral a => [a] -> Int
j [] = 0
j xs = if (head (tail (reverse xs)) < last xs)
          then (length xs)-2
          else j (take (length xs - 1) xs)


Does anyone has a more elegant solution for this first step?