I hadn't noticed the permutation function. It's not listed in the synopis... Nice.<br><br>Anyway, I found a better way around my little exercise.<br><br>import List<br>import Maybe<br><br>j :: Integral a => [a] -> Int<br>
<br>j xs = (fromMaybe 0 (findIndex (==False) (zipWith (<) (init xs) (tail xs)))) - 1<br><br><br><br><br><div class="gmail_quote">On Mon, Mar 8, 2010 at 9:29 AM, Daniel Fischer <span dir="ltr"><<a href="mailto:daniel.is.fischer@web.de">daniel.is.fischer@web.de</a>></span> wrote:<br>
<blockquote class="gmail_quote" style="margin: 0pt 0pt 0pt 0.8ex; border-left: 1px solid rgb(204, 204, 204); padding-left: 1ex;">Am Montag 08 März 2010 14:49:15 schrieb Nicolas Couture-Grenier:<br>
<div class="im">> I'm learning Haskell and I'm trying to translate a pseudocode algorithm<br>
> to generate the next permutation from a previous permutation.<br>
<br>
</div>Don't try to translate it directly. In Haskell, generally a different<br>
approach than for imperative (pseudo-) code is better.<br>
<div class="im"><br>
><br>
> A permutation is a list of n numbers (let's call it a) in {1 .. n}<br>
> appearing once in arbitrary order.<br>
><br>
> The first step is to find the largest index j in the list for which a[j]<br>
> < a[j+1].<br>
><br>
> The pseudocode is simple:<br>
><br>
> j:= n-1<br>
><br>
> while a[j] > a[j+1]<br>
> j:=j-1<br>
><br>
><br>
> I've coded a haskell function to do this, but it is much uglier than the<br>
> pseudocode :<br>
<br>
</div>It's not appropriate for lists, therefore, it's ugly. You can work with<br>
arrays and have a fairly direct correspondence:<br>
<br>
import Data.Array<br>
<br>
fun :: Array Int Int -> Int<br>
fun a = go (hi-1)<br>
where<br>
(lo,hi) = bounds a<br>
go i<br>
| i < lo = i<br>
| a!i > a!(i+1) = go (i-1)<br>
| otherwise = i<br>
<br>
The local "go" is our while-loop, additionally, it checks that we don't<br>
fall off the front of the array.<br>
<br>
When working with lists, one would typically not produce the next<br>
permutation from the previous, but generate the list of all permutations<br>
(take a look at the code of "permutations" in Data.List).<br>
<div><div></div><div class="h5"><br>
><br>
> j :: Integral a => [a] -> Int<br>
> j [] = 0<br>
> j xs = if (head (tail (reverse xs)) < last xs)<br>
> then (length xs)-2<br>
> else j (take (length xs - 1) xs)<br>
><br>
><br>
> Does anyone has a more elegant solution for this first step?<br>
<br>
</div></div></blockquote></div><br>