[Haskell-cafe] how to print out intermediate results in a recursive function?

MigMit miguelimo38 at yandex.ru
Sat Feb 4 09:46:53 CET 2012


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)  

On 4 Feb 2012, at 22:23, Qi Qi wrote:

> Hello,
> 
> I have a question;how can I print out the intermediate number lists in a
> mergesort recursive function like the following one.
> 
> merge [] ys = ys
> merge xs [] = xs
> merge (x:xs) (y:ys) = if x <= y
>                      then x : merge xs (y:ys)
>                      else y : merge (x:xs) ys
> 
> mergesort [] = []
> mergesort [x] = [x]
> mergesort xs = let (as, bs) = splitAt (length xs `quot` 2) xs
>               in merge (mergesort as) (mergesort bs)
> 
> main = do
>       print $ mergesort [5,4,3,2,1]
> 
> 
> In the main function, it only prints out the final number list. But I'd
> like to print out the number lists in every recursive level. How can I
> do that? Thanks.
> 
> 
> -- 
> Qi Qi
> 
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe




More information about the Haskell-Cafe mailing list