Llayland’s Food, Oracle, and Haskell

April 11, 2012

Trying to learn FRP 4 (stepped macros)

Filed under: Haskell — Tags: , , — llayland @ 2:15 am

The game in the last post worked, but the macros jumped to their target instead of following each step.  If we upgrade to Reactive-Banana 0.5, we can use the spill function to get an event that fires with the values of an array in sequence.

Thanks to Heinrich Apfelmus for clarifying that this usage is valid.

The rules of the game:

The user starts at the point (1,0)
Moving onto a point on the x=y line loses
moving onto the point (6,4) wins
The commands UP,DOWN,LEFT,RIGHT move the user
The command DEF <name> <string>…  defines macros
The command UNDEF String removes a macro
macros may refer to other macros

I moved the relevant FRP parts to the begining, but I still need the imports first

> import Reactive.Banana
> import Control.Monad
> import Data.Monoid
> import qualified Data.Map as Map
> import Prelude hiding (Left,Right)
> import Data.IORef   — I wish I could get rid of this

> networkDescription :: (IORef GameCondition) -> NetworkDescription t (Event t String) -> NetworkDescription t ()
> networkDescription condRef lineEnd = do
>    lineE <- lineEnd

The filterJust function fits nicely with our parse functions to create events that only fire on a successful parse

>    let defE = filterJust $ parseDef . words <$> lineE
>        undefE = filterJust $ parseUndef . words <$> lineE

The current dictionary is just the accumulation of the updates from the successful parses

>        dictB = accumB initialDict $ defE `union` undefE

We need both a behavior for the players position and an event that fires when we update the behavior.
A combinator for this is easy to build on top of the mapAccum combinator.

>        accumEB :: a -> Event t (a->a) -> (Event t a, Behavior t a)
>        accumEB seed e = mapAccum seed (fmap (\f -> pairAp f) e)
>           where pairAp f a = (f a, f a)

Here is the updated functionality to step through the macros.
We need to fire an event containing the list of steps in response to an entered line event.
Then, we spill that event to fire a sequence of events each containing a step.

>        stepsE = getMove <$> dictB <@> lineE
>        stepsEs = spill stepsE

We can determine the position with the sequence just like we did with the old aggregated event

>        (positionE, positionB) = accumEB (Sum 1, Sum 0) $ fmap mappend stepsEs

now we can fire events when the player reaches a position

>        loseE = filterE (uncurry (==)) positionE
>        winE = filterE (== (Sum 6, Sum 4)) positionE
>        quitE = filterE (== “quit”) lineE

Last, we react to some of the events.

>        exitWith retval = reactimate . fmap (const $ writeIORef condRef retval)
>
>    reactimate $ fmap print positionE
>    exitWith Lost loseE
>    exitWith Won winE
>    exitWith Quit quitE

Once again this was very easy. Here is a sample output to verify the change:

*Main> main
def n Up
(Sum {getSum = 1},Sum {getSum = 0})
def e Right
(Sum {getSum = 1},Sum {getSum = 0})
def wl e e e e e n n n n n n n n
(Sum {getSum = 1},Sum {getSum = 0})
wl
(Sum {getSum = 2},Sum {getSum = 0})
(Sum {getSum = 3},Sum {getSum = 0})
(Sum {getSum = 4},Sum {getSum = 0})
(Sum {getSum = 5},Sum {getSum = 0})
(Sum {getSum = 6},Sum {getSum = 0})
(Sum {getSum = 6},Sum {getSum = 1})
(Sum {getSum = 6},Sum {getSum = 2})
(Sum {getSum = 6},Sum {getSum = 3})
(Sum {getSum = 6},Sum {getSum = 4})
(Sum {getSum = 6},Sum {getSum = 5})
(Sum {getSum = 6},Sum {getSum = 6})
(Sum {getSum = 6},Sum {getSum = 7})
(Sum {getSum = 6},Sum {getSum = 8})
You Won

Notice that output continued after I won. I’ll fix that in the next post.

I’m not sure why I did not get a lost message when I hit (6,6); lazyness?

> eventLoop condRef fire = loop
>    where
>    loop = do
>       s <- getLine
>       fire s
>       cond <- readIORef condRef
>       when (cond == Playing) loop

> main = do
>   gameCondRef <- newIORef Playing
>   (addHandler,fire) <- newAddHandler
>   compile (networkDescription gameCondRef $ fromAddHandler addHandler ) >>= actuate
>   eventLoop gameCondRef fire
>   cond <- readIORef gameCondRef
>   putStrLn $ “You ” ++ show cond

Lets pull some types out of that desciption

> type XY = (Sum Int,Sum Int)

> data GameCondition = Won | Lost | Quit | Playing
>    deriving (Show, Eq)

> data Direction = Up | Down | Left | Right | Stay
>    deriving (Show, Enum)

> data Macro = Macro Direction
>            | Refs [String]
>    deriving Show

> type Dict = Map.Map String Macro

and the obvious functions

> xy :: Direction -> XY
> xy Up = (Sum 0,Sum 1); xy Down = (Sum 0,Sum (-1)); xy Left = (Sum (-1),Sum 0); xy Right = (Sum 1,Sum 0); xy Stay = (Sum 0, Sum 0)

> gameCond :: XY -> GameCondition
> gameCond p@(x,y) | x == y     = Lost
>                  | p == (Sum 6,Sum 4) = Won
>                  | otherwise  = Playing

> getMove :: Dict -> String -> [XY]
> getMove d k = case Map.lookup k d of
>                 Nothing -> [xy Stay]
>                 Just (Macro m) -> [xy m]
>                 Just (Refs rs) -> concatMap (getMove d) $ rs

> parseDef :: [String] -> Maybe (Dict -> Dict)
> parseDef (“def”:name:rs) = Just $ Map.insert name (Refs rs)
> parseDef _ = Nothing

> parseUndef :: [String] -> Maybe (Dict -> Dict)
> parseUndef [“undef”,name] = Just $ Map.delete name
> parseUndef _ = Nothing

We’ll need to start with a dictionary containing the basic movement commands

> initialDict = Map.fromList . map namer $ [Up .. Right]
>   where namer x = (show x, Macro x)

April 9, 2012

Trying to learn FRP 3 (a simple “game”)

Filed under: Haskell — Tags: , , — llayland @ 4:40 am

In this post I’ll implement a simple “game” where the user must move on a grid from the origin to a given position.

Let’s get the boilerplate out of the way

> import Reactive.Banana
> import Control.Monad
> import Data.Monoid
> import qualified Data.Map as Map
> import Prelude hiding (Left,Right)
> import Data.IORef   — I wish I could get rid of this

> eventLoop condRef fire = loop
>    where
>    loop = do
>       s <- getLine
>       fire s
>       cond <- readIORef condRef
>       when (cond == Playing) loop

> main = do
>   gameCondRef <- newIORef Playing
>   (addHandler,fire) <- newAddHandler
>   compile (networkDescription gameCondRef $ fromAddHandler addHandler ) >>= actuate
>   eventLoop gameCondRef fire
>   cond <- readIORef gameCondRef
>   putStrLn $ “You ” ++ show cond

The user starts at the point (1,0)
Moving onto a point on the x=y line loses
moving onto the point (6,4) wins
The commands UP,DOWN,LEFT,RIGHT move the user
The command DEF <name> <string>…  defines macros
The command UNDEF String removes a macro
macros may refer to other macros

Lets pull some types out of that desciption

> type XY = (Sum Int,Sum Int)

> data GameCondition = Won | Lost | Quit | Playing
>    deriving (Show, Eq)

> data Direction = Up | Down | Left | Right | Stay
>    deriving (Show, Enum)

> data Macro = Macro Direction
>            | Refs [String]
>    deriving Show

> type Dict = Map.Map String Macro

and the obvious functions

> xy :: Direction -> XY
> xy Up = (Sum 0,Sum 1); xy Down = (Sum 0,Sum (-1)); xy Left = (Sum (-1),Sum 0); xy Right = (Sum 1,Sum 0); xy Stay = (Sum 0, Sum 0)

> gameCond :: XY -> GameCondition
> gameCond p@(x,y) | x == y     = Lost
>                  | p == (Sum 6,Sum 4) = Won
>                  | otherwise  = Playing

> getMove :: Dict -> String -> XY
> getMove d k = case Map.lookup k d of
>                 Nothing -> xy Stay
>                 Just (Macro m) -> xy m
>                 Just (Refs rs) -> mconcat . map (getMove d) $ rs

> parseDef :: [String] -> Maybe (Dict -> Dict)
> parseDef (“def”:name:rs) = Just $ Map.insert name (Refs rs)
> parseDef _ = Nothing

> parseUndef :: [String] -> Maybe (Dict -> Dict)
> parseUndef [“undef”,name] = Just $ Map.delete name
> parseUndef _ = Nothing

We’ll need to start with a dictionary containing the basic movement commands

> initialDict = Map.fromList . map namer $ [Up .. Right]
>   where namer x = (show x, Macro x)

Finally, we are at the FRP part.

> networkDescription :: (IORef GameCondition) -> NetworkDescription (Event String) -> NetworkDescription ()
> networkDescription condRef lineEnd = do
>    lineE <- lineEnd

The filterJust function fits nicely with our parse functions to create events that only fire on a successful parse

>    let defE = filterJust $ parseDef . words <$> lineE
>        undefE = filterJust $ parseUndef . words <$> lineE

The current dictionary is just the accumulation of the updates from the successful parses

>        dictB = accumB initialDict $ defE `union` undefE

We need both a behavior for the players position and an event that fires when we update the behavior.
A combinator for this is easy to build on top of the mapAccum combinator.

>        accumEB :: a -> Event (a->a) -> (Event a, Behavior a)
>        accumEB seed e = mapAccum seed (fmap (\f -> pairAp f) e)
>           where pairAp f a = (f a, f a)
>        (positionE, positionB) = accumEB (Sum 1, Sum 0) (fmap mappend $ getMove <$> dictB <@> lineE)

now we can fire events when the player reaches a position

>        loseE = filterE (uncurry (==)) positionE
>        winE = filterE (== (Sum 6, Sum 4)) positionE
>        quitE = filterE (== “quit”) lineE

Last, we react to some of the events.

>        exitWith retval = reactimate . fmap (const $ writeIORef condRef retval)
>
>    reactimate $ fmap print positionE
>    exitWith Lost loseE
>    exitWith Won winE
>    exitWith Quit quitE

That was easier than I thought it would be. I would like to find a better way to communicate back to the event loop than IORefs.
Other than that, I like this code.

March 28, 2012

Trying to figure out FRP 2 (Behaviors)

Filed under: Haskell — Tags: , , — llayland @ 3:32 am

In the last post I created a simple echo program using just events.  In this post I introduce behaviors which are time varying values.

Let’s get the boilerplate out of the way

> import Reactive.Banana
> import Control.Monad
> import Data.Monoid

> eventLoop fire = loop
>    where
>    loop = do
>       s <- getLine
>       fire s
>       when (s /= “quit”) loop

> main = do
>   (addHandler,fire) <- newAddHandler
>   compile (networkDescription $ fromAddHandler addHandler ) >>= actuate
>   eventLoop fire

> networkDescription lineEnd = do
>   let run p f = lineEnd >>= \a -> reactimate $ fmap f (filterE p a)
>   run (/=”quit”) $ putStrLn . (“You typed: “++)
>   run (==”quit”) $ const (putStrLn “Goodbye”)

Let’s make a series of behaviours, starting with a behaviour that is constantly 1:

>   let oneB :: Behavior Integer
>       oneB = pure 1

Displaying a behaviors value took a little thinking to figure out.  Behaviors are continous functions of time, so there is no function to transform one to an event.
What we can do is apply a function in a behavior to the value in an event.

>   let bToE :: Behavior a -> Event b -> Event a
>       bToE b = apply  (const <$> b)
>       oneE = bToE oneB

Then we can output the transformed event.

>   let outpB e b f = e >>= \a -> reactimate $ fmap f (bToE b a)
>   outpB lineEnd oneB $ putStrLn . (“oneB: ” ++) . show

We can create a behavior that changes values to an event’s value when it fires with the stepper function.

>   lineE <- lineEnd
>   let lineB =  stepper “” lineE
>   outpB lineEnd lineB $ putStrLn . (“lineB: ” ++) . show

Events form a monoid that we can use to create a behavior that changes value with either of two events.

>   let ynB = stepper “N” $ filterE (==”Y”) lineE
>                 `mappend` filterE (==”N”) lineE
>   outpB lineEnd ynB $ putStrLn . (“ynB: ” ++) . show

We can also create behaviors that fold a function valued event. This is good for accumulating updates.
For example, an increment event can be used to get a count of commands given

>   let incE = fmap (const (+1)) lineE
>       countB = accumB 0 incE

>   outpB lineEnd countB $ putStrLn . (“countB: ” ++) . show

We are not limitted to single updates

>   let undoE = fmap (const (subtract 2)) $ filterE (==”undo”) lineE
>       realCountB = accumB 0 $ incE `mappend` undoE

>   outpB lineEnd realCountB $ putStrLn . (“realCountB: ” ++) . show

This last example shows the promise of FRP. We can specify a complex behavior that involves multiple events declaratively and in one place.

March 25, 2012

Trying to figure out FRP

Filed under: Haskell — Tags: , , — llayland @ 10:12 pm

This is my attempt at learning FRP and sharing as I go.

I’ll be using Reactive-Banana as it looks simple and seems to have the most activity.

> import Reactive.Banana
> import Control.Monad

To keep things simple I will forgo a gui library. A console application is not the usual target for FRP programs, but it allows me to focus on the logic instead of the framework.
So, we need an event loop for the console that will allow us to fire events.

> eventLoop fire = loop
>    where
>    loop = do
>       s <- getLine
>       fire s
>       when (s /= “quit”) loop

A non FRP implementation of our program is very simple; simply make the fire function generate an IO action:

> echoNonFRP = eventLoop $ putStrLn . (“You typed: “++)

In this trivial example, it makes sense to handle the input right here. FRP is definitely overkill, but I will implement an FRP solution to show how it allows us to seperate the firing of an event from response to the event.

> echoFRP = do

first we use the newAddHandler action to generate a pair of a handler and a firing function. These are linked together somehow so that the handler can be used to recognize events that are created by the firing function

>   (addHandler,fire) <- newAddHandler

we can use the addhandler to build a network description. We’ll flesh out the details of the description later.  For now, we just compile it into a nework and then actuate the network to turn it into an IO action.

>   compile (fromAddHandler addHandler >>= networkDescription’) >>= actuate

The type of fire (a -> IO ()) is exactly what we need to pass into our eventLoop.

>   eventLoop fire

Now we just need to fill in our network description. The reactimate function is used to emit the value of an event when it occurs. We need an IO action instead of a String, so we map a function (a -> IO) over the event.

> networkDescription’ lineE = reactimate $ fmap (putStrLn . (“You typed: “++)) lineE

and that is it. This functions identically to the non FRP version.

here it is without interuption and special handling for the quit command:

> networkDescription lineE = do
>   let run p f = lineE >>= \a -> reactimate $ fmap f (filterE p a)
>   run (/=”quit”) $ putStrLn . (“You typed: “++)
>   run (==”quit”) $ const (putStrLn “Goodbye”)

> echo = do
>   (addHandler,fire) <- newAddHandler
>   compile (networkDescription $ fromAddHandler addHandler ) >>= actuate
>   eventLoop fire

Create a free website or blog at WordPress.com.