[Haskell-cafe] Re: Is lazyness make big difference?

apfelmus at quantentunnel.de apfelmus at quantentunnel.de
Thu Feb 15 07:57:29 EST 2007


Allan Clark wrote:
> For me one of the best examples of this is that of logging within a
> compiler.
> Consider a compiler which operates roughly as such
> 
> compileProgram :: String -> IO ()
> compileProgram program =
>  let (log, abstract) = parse program
>       (log2, typedProgram) = typeCheck abstract log
>       (log3, convertedProgram) = convertToIntermediate typedProgram log2
>       (log4, convertedToAssembly) = convertToAssembly convertedProgram log3
>  in do writeFile "a.asm" (show convertedToAssembly)
>           writeFile "a.log" (show log4)
> 
> Now each of the intermediate transforming calls will produce some
> logging information which is added to the current log.

It's a bit OT (off thread) but I think that it's better to appeal to the
monoid structure of logs

  let
    (log,  abstract    )        = parse program
    (log2, typedProgram)        = typeCheck abstract
    (log3, convertedProgram)    = convertToIntermediate typedProgram
    (log4, convertedToAssembly) = convertToAssembly convertedProgram
  in show (mconcat [log,log2,log3,log4])

i.e. to use Monad.Writer in stead of Monad.State. The point is that for
example 'typedProgram' does not really depend on the contents of 'log',
but the dependencies in your code don't express this. One should switch from

  Log -> (a, Log)

to

  (a, Log -> Log)

or even

  (a, Log)

if Log already has a natural monoid structure.


Regards,
apfelmus



More information about the Haskell-Cafe mailing list