[Haskell-beginners] dropWhile returning last dropped element

Bob Ippolito bob at redivi.com
Sat Apr 18 23:48:08 UTC 2015


On Sat, Apr 18, 2015 at 4:21 PM, Michael Orlitzky <michael at orlitzky.com>
wrote:

> On 04/18/2015 01:10 PM, martin wrote:
> > Am 04/17/2015 um 11:18 PM schrieb Michael Orlitzky:
> >
> >> Why do you want to avoid recursion? You could rewrite this to use list
> indices if you really wanted to, but anything
> >> you come up with is going to be essentially recursive, only less safe
> >
> > Thanks for the code sample and pointing out that there may not be any
> last dropped element.
> >
> > I was wondering if there is  to achive the desired behavior by plugging
> together higher-order functions. This was the
> > only reason why I wanted to avoid explicit recursion.
> >
>
> Sure. Whenever you're processing a list and building up a return value,
> it's probably a (left) fold. But a fold would pointlessly process the
> rest of the list after it had stopped dropping elements, violating one
> of your criteria. And foldl is of course implemented recursively =)
>
> A "short-circuiting" version of foldl might exist in some library, but
> there are a few ways I can think of to implement it, so it might be hard
> to find.


You don't need a left fold for this. It's a bit awkward but you can indeed
just combine functions. Here's one way to write it that should not suffer
from any sort of pointless list processing.

import Data.List (tails)
import Data.Maybe (listToMaybe)

dropWhileWithLast :: (a -> Bool) -> [a] -> (Maybe a, [a])
dropWhileWithLast f xs =
  -- Not partial. The last element of tails is [] and
  -- maybe False will guarantee a non-empty list.
  head .
  dropWhile (maybe False f . listToMaybe . snd) $
  zip (Nothing : map Just xs) (tails xs)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20150418/01919fce/attachment.html>


More information about the Beginners mailing list