[Haskell-beginners] Translating a while

Nicolas Couture-Grenier greniernic at gmail.com
Mon Mar 8 08:49:15 EST 2010


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?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/beginners/attachments/20100308/596fe75c/attachment.html


More information about the Beginners mailing list