[Haskell-beginners] Translating a while
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] <
> 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
j xs = maybeLast . filter snd . zip [0..] $ zipWith (<) xs (drop 1 xs)
maybeLast  = Nothing
maybeLast xs = Just (last xs)
Notice my use of the Maybe type - there might not be
any such index j at all.
> j:= n-1
> while a[j] > a[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
More information about the Beginners