Tuesday, February 18, 2014

Haskell GTK Example (Hello, world!)

I quite enjoy using Haskell, but from my own attempt, anything involving monads has proven to be quite nightmare-ish. Since it had been a while since I've played around in Haskell, I decided to look into something I had been reluctant to since I started, graphics. Upon looking at an example I thought would be simple, I found myself intimidated and flooded with stuff that I had no idea what it did. So I decided to find a hello world example, then rewrite it in a more readable fashion, at least in my opinion.

import Graphics.UI.Gtk

main :: IO ()
main =
    -- Start the graphics
    initGUI >>
    -- Create a new window object and do stuff
    windowNew >>= (\ window ->
        -- Quit when the window is gone
        onDestroy window mainQuit >>
        -- Set some window attributes
        set window [ containerBorderWidth := 10, windowTitle := "Hello, world!" ] >>
        -- So it has a decent size
        windowSetDefaultSize window 200 100 >>
        -- Now let's make a button
        buttonNew >>= (\ button ->
            set button [ buttonLabel := "Hello!" ] >>
            -- Multiple events can be assigned, they run in order
            onClicked button (widgetDestroy window) >>
            -- Put the button on the window
            set window [ containerChild := button ]) >>
        -- Display the window and contents
        widgetShowAll window) >>
    -- Actually run the graphics
    mainGUI

I chose to avoid ado notation because in the examples it looked sloppy and unreadable. Instead I used lambda functions along side monad sequencing functions (>> and  >>=). This has allowed me to explicitly separate the window setup and even the button setup in an attempt to avoid a procedural style with variable assignment.

It makes a window, the button makes it exit. Simple and clean.

Tag Cloud

.NET (1) A+ (2) addon (6) Android (3) anonymous functions (5) application (10) arduino (1) artificial intelligence (2) bash (4) c (7) camera (1) certifications (4) cobol (1) comptia (4) computing (2) css (2) customize (16) encryption (2) error (19) exploit (17) ftp (3) funny (2) gadget (2) games (2) Gtk (1) GUI (5) hardware (6) haskell (15) help (8) HTML (6) irc (2) java (5) javascript (21) Linux (19) Mac (4) malware (2) math (8) network (9) objects (2) OCaml (1) perl (4) php (9) plugin (7) programming (42) python (24) radio (1) regex (3) security (25) sound (1) speakers (1) ssh (3) story (1) Techs from the Crypt (2) telnet (2) tools (14) troubleshooting (5) Ubuntu (4) Unix (4) virtualization (1) web design (14) Windows (7) wx (2)