User:Echo Nolan/Reactive Banana: Straight to the Point

From HaskellWiki
Revision as of 17:45, 18 September 2012 by Echo Nolan (talk | contribs)

Jump to: navigation, search

Introduction

So I'm writing this tutorial as a means of teaching myself FRP and reactive-banana. It'll probably be full of errors and bad advice, use it at your own risk.

All the tutorials on FRP I've read start with a long boring theory section. This is an instant gratification article. For starters, imagine a man attempting to sharpen a banana into a deadly weapon. See? You're gratified already! Now for a boring bit:

Go install mplayer: <code-bash>apt-get install mplayer # Or equivalent</code-bash>

Get the git repository associated with this tutorial: <code-bash>git clone https://github.com/enolan/rbsttp.git </code-bash>

Install reactive-banana <code-bash> cabal install reactive-banana</code-bash>

Musical interlude

Cd into the git repo and open rbsttp.hs in GHCi:

<pre-bash> cd rbsttp ghci rbsttp.hs </pre-bash>

Now, we can make some beepy noises. Try these:

<pre-haskell> playNote C2 playNote C6 sequence_ . intersperse (threadDelay 1000000) $ map playNote [C2 ..] </pre-haskell>

Play with the value passed to threadDelay a bit for some more interesting noises. It's expresssed in microseconds.

<pre-haskell> sequence_ . intersperse (threadDelay 500000) $ map playNote [C2 ..] sequence_ . intersperse (threadDelay 250000) $ map playNote [C2 ..] sequence_ . intersperse (threadDelay 125000) $ map playNote [C2 ..] sequence_ . intersperse (threadDelay 62500) $ map playNote [C2 ..] </pre-haskell>

You've probably figured out by now that C2 and C6 are data constructors. Here's the definition for my Note type.

<pre-haskell> data Note = C2 | C3 | C4 | C5 | C6 deriving (Show, Enum) </pre-haskell>

<code-haskell>playNote</code-haskell> is the world's ugliest, hackiest synthesizer. Please don't look at its source. It's also asynchronous, which is why <code-haskell>mapM_ playNote [C2 ..] doesn't sound very interesting.

Hook our synth up to our keyboard

"But Echo!" I hear you say "that's all in the IO monad!" You're right. We're going to free our synthesizer from the depths of imperative IO monad programming into the glorious light of declarative programming soon.