I hadn&#39;t noticed the permutation function. It&#39;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 =&gt; [a] -&gt; Int<br>
<br>j xs = (fromMaybe 0 (findIndex (==False) (zipWith (&lt;) (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">&lt;<a href="mailto:daniel.is.fischer@web.de">daniel.is.fischer@web.de</a>&gt;</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">&gt; I&#39;m learning Haskell and I&#39;m trying to translate a pseudocode algorithm<br>
&gt; to generate the next permutation from a previous permutation.<br>
<br>
</div>Don&#39;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>
&gt;<br>
&gt; A permutation is a list of n numbers (let&#39;s call it a) in {1 .. n}<br>
&gt; appearing once in arbitrary order.<br>
&gt;<br>
&gt; The first step is to find the largest index j in the list for which a[j]<br>
&gt; &lt; a[j+1].<br>
&gt;<br>
&gt; The pseudocode is simple:<br>
&gt;<br>
&gt; j:= n-1<br>
&gt;<br>
&gt; while a[j] &gt; a[j+1]<br>
&gt;     j:=j-1<br>
&gt;<br>
&gt;<br>
&gt; I&#39;ve coded a haskell function to do this, but it is much uglier than the<br>
&gt; pseudocode :<br>
<br>
</div>It&#39;s not appropriate for lists, therefore, it&#39;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 -&gt; Int<br>
fun a = go (hi-1)<br>
   where<br>
      (lo,hi) = bounds a<br>
      go i<br>
        | i &lt; lo        = i<br>
        | a!i &gt; a!(i+1) = go (i-1)<br>
        | otherwise     = i<br>
<br>
The local &quot;go&quot; is our while-loop, additionally, it checks that we don&#39;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 &quot;permutations&quot; in Data.List).<br>
<div><div></div><div class="h5"><br>
&gt;<br>
&gt; j :: Integral a =&gt; [a] -&gt; Int<br>
&gt; j [] = 0<br>
&gt; j xs = if (head (tail (reverse xs)) &lt; last xs)<br>
&gt;           then (length xs)-2<br>
&gt;           else j (take (length xs - 1) xs)<br>
&gt;<br>
&gt;<br>
&gt; Does anyone has a more elegant solution for this first step?<br>
<br>
</div></div></blockquote></div><br>