Wednesday, 21 August 2013

The possibility of a `while` function for Haskell list-like monads

The possibility of a `while` function for Haskell list-like monads

In Clojure, I can write something like this:
(for [x [1 2 3] :when (not= x 2)]
x)
and get back the vector [1 3]. Haskell has an equivalent using the guard
function:
do x <- [1, 2, 3]
guard $ x /= 2
return x
But Clojure also has a :while qualifier in its for macro, allowing me to
do this:
(for [x [1 2 3] :while (not= x 2)]
x)
and get back [1].
My question is: can you write a monad in Haskell with an analogous while
function? I.e., something that would let me write:
do x <- fromList [1, 2, 3]
while $ x /= 2
return x
and get back a value corresponding to the list [1]? If so, how? If not,
why not?
Note that I realize that you could directly call takeWhile on the list,
itself:
do x <- takeWhile (/= 2) [1, 2, 3]
return x
but I'm looking for something that acts more like guard.

No comments:

Post a Comment