[Haskell-cafe] "Hello World" in Haskell for web browser

Dimitry Golubovsky golubovsky at gmail.com
Thu Mar 6 22:05:01 EST 2008


I have noticed that some people tried to compile a traditional Haskell
program using IO monad to show "Hello World" using Yhc Web Service.

Thanks for your interest, and here are some clues.

The programming paradigm chosen for Haskell Web programming is not
based on monads. It is based on CPS-style calls to DOM functions by
Haskell code compiled to Javascript. Further on, additional layers may
stack up (such as Haskell Web Toolkit) to provide more convenient
APIs, but DOM is the basis.

So here is an example of "Hello World" program written this way:

-- begin pasteable code --

module HelloWorldDOM where

import CPS
import UnsafeJS
import CDOM.Level2.DomUtils
import DOM.Level2.Dom
import DOM.Level2.Html2
import DOM.Level2.HTMLElement
import DOM.Level2.HTMLDivElement

main = getHTMLDocument $ \doc ->
       documentBody doc $ \body ->
       mkText doc "Hello World" $ \txt ->
       mkDiv doc $ \dv ->
       addChild txt dv $ \_ ->
       addChild dv body $ id

-- end   pasteable code --

The meaning of this:
  * get reference to the HTML document node first (it is the parent of
  * extract the <BODY> tag node, create at text element with "Hello World",
  * create a <DIV> tag node,
  * insert the text node into div,
  * insert div into body

Or, same in HTML:

      Hello World

but filled in dynamically.

Using Haskell Web Toolkit API, the same may be expressed in more
compact fashion:

-- begin pasteable code --

module HelloWorldHsWTK where

import DOM.Level2.HTMLDivElement
import Graphics.UI.HsWTK

main = docBodyC (mkDiv |<< textP "Hello World")

-- end   pasteable code --

Here, docBodyC is roughly equivalent of the first two DOM calls, mkDiv
is same as above, |<< means "insert into container", and textP is a
wrapper around mkText.

Earlier, I posted the link to Haddock-generated documentation which
also includes the Haskell DOM API. Here it is again:


Hopefully this example along with the documentation provided helps
shed some light on Haskell Web programming techniques.

Feel free to ask questions.


Dimitry Golubovsky

Anywhere on the Web

More information about the Haskell-Cafe mailing list