[Haskell-beginners] Haskeline and forkIO

Heinrich Apfelmus apfelmus at quantentunnel.de
Wed Aug 27 09:00:53 UTC 2014


Jeff C. Britton wrote:
> I am trying to modify an example in RealWorldHaskell from Chapter 24.
> The example is the first code snippet labeled -- file: ch24/Compressor.hs
> 
> I am trying to replace the use of Readline with Haskeline.
> In my code the forkIO thread does not run.
> I guessed that since the result of the worker thread was thrown away that perhaps laziness was the problem.
> So, I attempted to use `seq`, but that does not work either.

The forkIO is not run because your code never actually runs it. :)

The snippet

    let f = runWorker (worker path)
    in
        f `seq` do
          return f
          loop

binds a value (here an `IO` action) to the variable `f`, then makes sure 
that the variable is evaluated to weak head normal form (which is 
something quite different from executing the `IO` action), and then 
combines the IO action `return f` (which has no side effects, but 
returns the value of `f`) with `loop`.

The key point to understand here is that IO actions are first-class 
values: you can bind them to variables and combine them with `>>` and 
`>>=`. In a sense, you never execute IO actions, you only build them. 
The only time when something is executed is when the Haskell compiler 
executes the IO action assigned to the `main` variable.

What you had in mind is a program that combines the IO action `f` 
directly with the `loop`, like this:

    let f = runWorker (worker path)
    in
        do
          f
          loop


Best regards,
Heinrich Apfelmus

--
http://apfelmus.nfshost.com



More information about the Beginners mailing list