Sunday, November 30, 2008

F# LegoNxt Robot


I am learning F# since 07/2007 and looked always for an opportunity to put my F# coding skills in to practice. I grabbed my son’s Lego Nxt and wrote a library in F# to communicate with Lego Nxt Brick via Blue Tooth . I have added support for two moving motors (Port B and C) , touch sensor (Port 1) and sonar sensor(Port4). Joe Armstrong (Erlang Programming Language) told in an interview something like this :
In a real world, people also act concurrently from one another and this all works fine and we don’t need to be Siamese twins with conjoined brains(hint :shared memory). I am using Erlang style Message Passing Style using F# MailboxProcessor for collecting data and to control nxt robot.
In source code , I have written an example AutonomousNxtBrick which will drive autonomic and avoid collision.

Enjoy

Thursday, November 13, 2008

F# MailboxProcessor

The Mailboxprocessor class has changed slightly in Version 1.9.6.2
You have to modify the example 13.11 from the Expert F# Book as following to run

#light
// ----------------------------
// Listing 13-11.
/// The internal type of messages for the agent
type internal msg = Increment of int Fetch of AsyncReplyChannel Stop
type CountingAgent() =
let counter = MailboxProcessor.Start(fun inbox ->
// The states of the message-processing state machine...
let rec loop(n) =
async { let! msg = inbox.Receive()
match msg with
Increment m ->
// increment and continue.
return! loop(n+m)
Stop ->
// exit
return ()
Fetch replyChannel ->
// post response to reply channel and continue
do replyChannel.Reply(n)
return! loop(n) }
// The initial state of the message-processing state machine...
loop(0))
member a.Increment(n) = counter.Post(Increment(n))
member a.Stop() = counter.Post(Stop)
member a.Fetch() = counter.PostAndReply(fun replyChannel -> Fetch(replyChannel))
// ----------------------------
let counter = new CountingAgent()
counter.Increment(1)
let v=counter.Fetch()
printfn "%d" v
counter.Increment(2)
let s=counter.Fetch()
printfn "%d" s
counter.Stop()