Proposal: Add sequenceWhile and SequenceWhile_ to Control.Monad

Dominic Steinitz dominic at steinitz.org
Sat May 9 13:04:13 EDT 2009


Sittampalam, Ganesh wrote:
> Dominic Steinitz wrote:
>> I'm not sure of the protocol for adding things to existing libraries
> 
> http://www.haskell.org/haskellwiki/Library_submissions
> 
> Though my general preference is to kick around an idea on here for a
> while first before starting the formal process.
> 
>> but I'd like to propose the addition of these two functions to
>> Control.Monad. 
>>
>> sequenceWhile_ :: Monad m => (a -> Bool) -> [m a] -> m ()
>> sequenceWhile_ _ [] =
>>   return ()
>> sequenceWhile_ p (x:xs) =
>>   x >>= \c -> if (p c) then sequenceWhile_ p xs else return ()
>>
>> sequenceWhile :: Monad m => (a -> Bool) -> [m a] -> m [a]
>> sequenceWhile _ [] =
>>   return []
>> sequenceWhile p (x:xs) = do
>>   y <- x
>>   if (p y)
>>     then do
>>       ys <- sequenceWhile p xs
>>       return (y:ys)
>>     else
>>       return [y]
> 
> This last line should probably be return [] for consistency with
> takeWhile etc. The downside of that is that the monadic effect
> associating with producing y has been run but then the value is thrown
> away.

I use sequenceWhile to go through actions and stop at the one that
"fails" (in some sense). I like to know what caused the failure so I
return [y]. It did occur to me that one could argue that it should
return []. But then you know something "failed" but not how.

> 
> It's also a bit specialised for my taste. A better option would be to
> have a takeWhileM which would allow sequenceWhile_ and sequenceWhile to
> be built from that and sequence_/sequence.

I'd argue that some of the functions in Control.Monad are more specialised.

I'm not sure what you had in mind for takeWhileM. Can you give a type
signature / behaviour description?

I'd be happy with the composition of two library functions *provided* I
can get hold of the value of the last run action.

Thanks for the feedback, Dominic.



More information about the Libraries mailing list