Sodium FRP simplest example

posted on 2014-11-20

The Sodium Functional Reactive Programming library seems simple enough, but as a Haskell beginner it was hard to get something simple that works.

Well, turns out it is as simple as:

module Main where
import FRP.Sodium

main :: IO()
main = do
    (line, addLine) <- sync newEvent
    unlisten <- sync $ listen line putStrLn
    sync $ addLine "hello"
    unlisten

This is much simpler then the poodle example that comes with Sodium and shows the most basic usage.

First a stream of events is created using newEvent. To get any of the -> Reactive () and -> Reactive a functions to work, you need the sync function to wrap it in the IO monad.

What newEvent returns is a tuple of two values: first value is the event stream, second value is an -> Reactive () function that allows you to fire the event (add values to the event stream)

In the second line we make sure that when anything happens on the event stream (line) the function putStrLn is called. Again we need sync to get the IO monad wrapping we need to main.

The return value of the second line, unlisten, is actually a function that should be applied to unregister the function application when the event is called. Being a well brought up developer, we call that at the end of our program.

At the third line we have everything set up and fire our first Event stream value. If everything went well, we get putStrLn called with a single String with value hello.

Trying something simple

A simple next step is to duplicate the second line: two unlistens and two putStrLns registered. Like so:

main = do
    (line, addLine) <- sync newEvent
    unlisten <- sync $ listen line putStrLn
    unlisten2 <- sync $ listen line putStrLn
    sync $ addLine "hello"
    unlisten
    unlisten2

And, as expected, we get "hello" put on the screen twice!

Where to now

My plan is creating a FRP based static site generator using either an event driven database or simply inotify to get on-demand minimum effort updates for my site. But there are only so many hours in the day. That is for a much later post.