[Haskell-cafe] applicative challenge
Tillmann Rendel
rendel at cs.au.dk
Mon May 4 17:58:56 EDT 2009
Thomas Hartman wrote:
> -- Can the function below be tweaked to quit on blank input,
> provisioned in the applicative style?
No. Applicative on its own does not support to decide which action to
take based on the result of some previous action. It is therefore not
possible to look at the last line read, and read another line or stop
processing depending on whether the last line was empty or not. You need
something beyond Applicative to do that.
> -- Can you tell/guess which function(s) is the problem just by looking
> at the code below?
repeat creates an infinite list, and sequence is strict, so ( sequence .
repeat $ ...) diverges. fmap for IO is strict in its second argument, so
notQuiteRight diverges.
repeat, sequence and fmap work together to make this expression diverge,
so I would not say that one of them is more problematic then the others.
> -- If so, can you explain what the strategy for doing so is?
No.
> notQuiteRight = takeWhile (not . blank) <$> ( sequence . repeat $ echo )
>
> echo = do
> l <- getLine
> putStrLn l
> return l
>
>
> -- this seems to work... is there a way to make it work Applicatively,
> with lifted takeWhile?
> seemsToWork = sequenceWhile_ (not . blank) (repeat echo)
>
> sequenceWhile_ p [] = return ()
> sequenceWhile_ p (mx:mxs) = do
> x <- mx
> if p x
> then do sequenceWhile_ p mxs
> else return ()
While this should work and looks like a reasonable implementation, it is
clearly not in Applicative style, since you use bind to look at the x.
Tillmann
More information about the Haskell-Cafe
mailing list