[Haskell-beginners] Translating a while

Yitzchak Gale gale at sefer.org
Mon Mar 8 09:38:27 EST 2010


Nicolas Couture-Grenier <greniernic at gmail.com> wrote:
> The first step is to find the largest index j in the list for which a[j] <
> a[j+1].
> The pseudocode is simple...

The pseudo-code represents how you would write this
algorithm in an imperative language. If you take the whole
algorithm and express it naturally in Haskell, that would likely
not be the first step at all.

But in any case, I might write that version of the first step
like this:

j xs = maybeLast . filter snd . zip [0..] $ zipWith (<) xs (drop 1 xs)
  where
    maybeLast [] = Nothing
    maybeLast xs = Just (last xs)

Notice my use of the Maybe type - there might not be
any such index j at all.

Regards,
Yitz
>
> 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?
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>
>


More information about the Beginners mailing list