[Haskell-cafe] how to print out intermediate results in a recursive function?
Steve Horne
sh006d3592 at blueyonder.co.uk
Sat Feb 4 12:54:44 CET 2012
On 04/02/2012 08:46, MigMit wrote:
> Well, if you want that in production, not for debugging purposes, you should change the type signature of mergesort so that it uses some monad. Printing requires IO monad; however, I would advise to collect all intermediate results using Writer monad, and print them afterwards:
>
> mergesort [] = return []
> mergesort [x] = return [x]
> mergesort xs = do
> tell [xs] -- that's right, "[xs]", not "xs"
> let (as, bs) = splitAt (length xs `quot` 2) xs
> liftM2 merge (mergesort as) (mergesort bs)
Also, don't forget that IO actions are values too. IOW, your list of
intermediate results can be a list of IO actions, effectively deferring
their "execution" until later.
More information about the Haskell-Cafe
mailing list