<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Kotan Code　枯淡コード</title>
	
	<link>http://www.kotancode.com</link>
	<description>In search of simple, elegant code</description>
	<lastBuildDate>Mon, 20 Feb 2012 17:32:48 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/KotanCode" /><feedburner:info uri="kotancode" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
		<title>Refactoring Imperative Code to List Comprehensions in Scala</title>
		<link>http://feedproxy.google.com/~r/KotanCode/~3/GrTQ3PCAoSM/</link>
		<comments>http://www.kotancode.com/2012/02/20/refactoring-imperative-code-to-list-comprehensions-in-scala/#comments</comments>
		<pubDate>Mon, 20 Feb 2012 17:32:48 +0000</pubDate>
		<dc:creator>Kevin Hoffman</dc:creator>
				<category><![CDATA[Languages]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[idiomatic]]></category>
		<category><![CDATA[list comprehensions]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[ScalaMUD]]></category>
		<category><![CDATA[stackoverflow]]></category>

		<guid isPermaLink="false">http://www.kotancode.com/?p=446</guid>
		<description><![CDATA[In my other series of posts about ScalaMUD, I&#8217;ve been writing a lot of code &#8211; some of it good, some of it ugly as hell. The reason a lot of the code looks ugly is that, as a C#, Java, and Objective-C developer my gut instinct is to do things in an imperative style [...]]]></description>
			<content:encoded><![CDATA[<p>In my<a title="ScalaMUD – More Multi-Threaded Command Parsing via Akka" href="http://www.kotancode.com/2012/02/20/scalamud-commands/" target="_blank"> other series of posts about ScalaMUD</a>, I&#8217;ve been writing a lot of code &#8211; some of it good, some of it ugly as hell. The reason a lot of the code looks ugly is that, as a C#, Java, and Objective-C developer my gut instinct is to do things in an imperative style with if statements, for loops, and other such constructs that simply don&#8217;t look at home in a hybrid functional language like Scala.</p>
<p>Here&#8217;s the code I originally produced, which scans through a list of NLP-tagged words and retrieves the first verb. If the list is empty then we need to return an empty string and if the list has no verbs then we assume that the first (or only) word in the list is a verb. For example, if I type &#8220;who&#8221; or &#8220;uptime&#8221; into the game then these should be considered verbs for command dispatching, even though NLP says they&#8217;re not verbs per se.</p>
<p><strong>Ugly as Sin Code:</strong></p>
<pre class="brush: java; title: ; notranslate">
def firstVerb = {
if (words.size == 1)
words.head.value
else {
val outWords = words.filter( word =&gt; word.pos == Verb)
if (outWords == Set.empty)
words.head.value
else
outWords.head.value
}
}
</pre>
<p>And thanks to the geniuses over at <a href="http://stackoverflow.com/questions/9362952/idiomatic-scala-list-comprehension-first-item-that-matches" target="_blank">Stack Overflow</a>, they were able to guide me to this incredibly simple, elegant refactoring:</p>
<p><strong>Refactored Code:</strong></p>
<pre class="brush: java; title: ; notranslate">
words find(_.pos == Verb) orElse words.headOption map(_.value) getOrElse &quot;&quot;
</pre>
<p>My hope is that someday I will think in terms of the second, more clean and refactored version and not instinctively reach for my imperative crutches.</p>
<img src="http://feeds.feedburner.com/~r/KotanCode/~4/GrTQ3PCAoSM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.kotancode.com/2012/02/20/refactoring-imperative-code-to-list-comprehensions-in-scala/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.kotancode.com/2012/02/20/refactoring-imperative-code-to-list-comprehensions-in-scala/</feedburner:origLink></item>
		<item>
		<title>ScalaMUD – More Multi-Threaded Command Parsing via Akka</title>
		<link>http://feedproxy.google.com/~r/KotanCode/~3/zb_QhTY5Mvc/</link>
		<comments>http://www.kotancode.com/2012/02/20/scalamud-commands/#comments</comments>
		<pubDate>Mon, 20 Feb 2012 17:17:55 +0000</pubDate>
		<dc:creator>Kevin Hoffman</dc:creator>
				<category><![CDATA[Languages]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[akka]]></category>
		<category><![CDATA[commands]]></category>
		<category><![CDATA[grammar]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[mud]]></category>
		<category><![CDATA[nlp]]></category>
		<category><![CDATA[parsing]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[ScalaMUD]]></category>

		<guid isPermaLink="false">http://www.kotancode.com/?p=440</guid>
		<description><![CDATA[In the last blog post on ScalaMUD, I showed how I was able to take advantage of a third party NLP library so that I could tag player input with the appropriate parts of speech like Verb, Noun, Adjective, etc. My goal here is to eventually use this information to match words in player input [...]]]></description>
			<content:encoded><![CDATA[<p>In the last blog post on ScalaMUD, I showed how I was able to take advantage of a third party NLP library so that I could tag player input with the appropriate parts of speech like Verb, Noun, Adjective, etc. My goal here is to eventually use this information to match words in player input sentences with physical objects in the game so that when someone types &#8216;kill the blue dragon&#8217;, I will be able to find the <strong>ActorRef</strong> for the blue dragon, and find a verb handler for <strong>kill</strong>, and then initiate combat.</p>
<p>In this blog post, I&#8217;ve come one step closer to that goal by enabling the dispatching of commands. As players enter input, that input is sent off to a <strong>Commander</strong> actor which tags up the input with parts of speech. Once the Comander is finished with it, it wraps the tagged words in an <strong>EnrichedCommand</strong> message and sends that to the player, which now has the trait <strong>Commandable</strong>, allowing the player to respond to enriched commands. This has an added benefit of allowing NPCs to be scripted in the future by allowing them to pretend to &#8216;type&#8217; things like &#8220;kill player&#8221;, etc.</p>
<p>Eventually rooms will add commands to players when they enter the room to allow them to type the name of the exit (e.g. north, south, up, window) as a verb. Mortals and Wizards alike each have a unique set of commands they need to be able to type and these commands are grouped into &#8220;command libraries&#8221; (my old alma mater MUD, <em>Genesis, an LPMUD</em>, called them <em>command souls</em>). For example, here&#8217;s the first version of the Mortal command lib:</p>
<pre class="brush: java; title: ; notranslate">
package com.kotancode.scalamud.core.cmd

import com.kotancode.scalamud.core.ServerStats
import com.kotancode.scalamud.core.TextMessage
import com.kotancode.scalamud.Game
import com.kotancode.scalamud.core.Implicits._
import akka.actor._
import akka.routing._

abstract class CommandLibMessage
case class AttachCommandLib extends CommandLibMessage

class MortalCommandLib extends Actor {
	def receive = handleMortalCommands

	def handleMortalCommands: Receive = {
		case cmd:EnrichedCommand if cmd.firstVerb == &quot;who&quot; =&gt; {
			handleWho(cmd.issuer)
		}
		case AttachCommandLib =&gt; {
			attachToSender(sender)
		}
	}

	def handleWho(issuer: ActorRef) = {
		println(&quot;player &quot;+ issuer.name + &quot; typed who.&quot;)
		var stringOut = &quot;Players logged in:\n&quot;
		for (p: ActorRef &lt;- Game.server.inventory) {
			stringOut += p.name + &quot;\n&quot;
		}
		issuer ! TextMessage(stringOut)
	}

	def attachToSender(sender:ActorRef) = {
		sender ! AddCommand(Set(&quot;who&quot;), self)
	}

}
</pre>
<p>Those of you who program in iOS or Cocoa might recognize some of the &#8220;Delegate Pattern&#8221; here&#8230; when the command lib attaches itself to something capable of issuing commands (anything that carries the <strong>Commandable</strong> trait, like a player or NPC), it just passes the implicit <em>sender</em> <strong>ActorRef</strong> so that actor can now dispatch commands to that lib.</p>
<p>Here&#8217;s the code in the <strong>Commander</strong> object that sends enriched commands to the actor that &#8220;typed&#8221; (virtually or for real) the command:</p>
<pre class="brush: java; title: ; notranslate">
package com.kotancode.scalamud.core.cmd

import akka.actor._
import akka.routing._

import com.kotancode.scalamud.core.lang.EnrichedWord
import java.util.ArrayList
import edu.stanford.nlp.ling.Sentence
import edu.stanford.nlp.ling.TaggedWord
import edu.stanford.nlp.ling.HasWord
import edu.stanford.nlp.tagger.maxent.MaxentTagger
import scala.collection.JavaConverters._
import scala.collection.mutable.ListBuffer
import com.kotancode.scalamud.core.cmd._

class Commander extends Actor {
	def receive = {
		case s:String =&gt; {
			val words = s.split(&quot; &quot;);
			val wordList = new java.util.ArrayList[String]();
			for (elem &lt;- words) wordList.add(elem)
		    val sentence = Sentence.toWordList(wordList);
		    val taggedSentence = Commander.tagger.tagSentence(sentence).asScala.toList

			var enrichedWords = new ListBuffer[EnrichedWord]
		    for (tw : TaggedWord &lt;- taggedSentence) {
				val ew = EnrichedWord(tw)
				println(ew)
				enrichedWords += ew
			}

			sender ! HandleCommand(EnrichedCommand(enrichedWords, sender))
	}
}
}

object Commander {
	val tagger = new MaxentTagger(&quot;models/english-bidirectional-distsim.tagger&quot;)
}
</pre>
<p>The important bit is that the player gets the <strong>HandleCommand</strong> message, which then goes through a dispatch process in the <strong>Commandable</strong> trait, and eventually registered verb handlers (like those registered via attached command libraries) get invoked via messages. Here&#8217;s the Commandable trait:</p>
<pre class="brush: java; title: ; notranslate">
package com.kotancode.scalamud.core.cmd

import akka.actor._
import akka.routing._
import scala.collection.mutable.HashMap
import scala.collection.mutable.HashSet

sealed abstract class CommandMessage
case class AddCommand(verbs:Set[String], handlerTarget:ActorRef) extends CommandMessage
case class Removecommand(verb:String) extends CommandMessage
case class HandleCommand(command:EnrichedCommand) extends CommandMessage

trait Commandable {

	private val verbHandlers: HashMap[Set[String], ActorRef] = new HashMap[Set[String], ActorRef]

	def handleCommandMessages:akka.actor.Actor.Receive = {
		case AddCommand(verbs, handlerTarget) =&gt; {
			verbHandlers.put(verbs, handlerTarget)
		}

		case HandleCommand(cmd) =&gt; {
			dispatch(cmd)
		}
	}

	def dispatch(cmd:EnrichedCommand) = {
		println(&quot;handled a command &quot;+ cmd +&quot;.&quot;)
		println(&quot;command's first verb: &quot; + cmd.firstVerb)
		val targetHandlers = verbHandlers.filterKeys(key =&gt; key.contains(cmd.firstVerb))
		targetHandlers foreach {case (key, value) =&gt; value ! cmd}
	}
}
</pre>
<p>The dispatching actually happens in the <strong>targetHandlers foreach &#8230;</strong> line where the command is sent to every command handler that declared interest in that verb. In our case, we have a mortal command verb <strong>who</strong> that displays the list of connected users and the wizard command verb <strong>uptime</strong> that displays the length of time the server app has been running.</p>
<p>The following is sample session output from telnetting to the game:</p>
<pre>Welcome to ScalaMUD 1.0

Login: Kevin
Welcome to ScalaMUD, Kevin
who
Kevin: who
Players logged in:
Bob
Kevin
Kevin
uptime
Kevin: uptime
Server has been up for 6 mins 39 secs.</pre>
<p>Now that I can log in with multiple players, see who is online, and dispatch commands to handlers as well as differentiate between mortal and wizard abilities, this game is finally starting to feel like the beginnings of a real MUD.</p>
<img src="http://feeds.feedburner.com/~r/KotanCode/~4/zb_QhTY5Mvc" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.kotancode.com/2012/02/20/scalamud-commands/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.kotancode.com/2012/02/20/scalamud-commands/</feedburner:origLink></item>
		<item>
		<title>iOS and Mac OS X Convergence Continues with Mountain Lion</title>
		<link>http://feedproxy.google.com/~r/KotanCode/~3/jIfbUVrGaCU/</link>
		<comments>http://www.kotancode.com/2012/02/17/ios-mountain-lion-convergence-mac/#comments</comments>
		<pubDate>Fri, 17 Feb 2012 12:57:08 +0000</pubDate>
		<dc:creator>Kevin Hoffman</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[apple]]></category>
		<category><![CDATA[gamekit]]></category>
		<category><![CDATA[iCloud]]></category>
		<category><![CDATA[ios]]></category>
		<category><![CDATA[ipad]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[lion]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[mountain lion]]></category>
		<category><![CDATA[osx]]></category>
		<category><![CDATA[twitter]]></category>

		<guid isPermaLink="false">http://www.kotancode.com/?p=435</guid>
		<description><![CDATA[Just the other day, Apple announced the major features coming up in their new operating system release, Mac OS X Mountain Lion. Before going into details on Mountain Lion, it&#8217;s worth remembering here that less than a year ago, Apple released Lion, which included a host of features that it borrowed from the iPad, including [...]]]></description>
			<content:encoded><![CDATA[<p>Just the other day, Apple announced the major features coming up in their new operating system release, <em>Mac OS X Mountain Lion</em>. Before going into details on Mountain Lion, it&#8217;s worth remembering here that less than a year ago, Apple released <em>Lion</em>, which included a host of features that it borrowed from the iPad, including <strong>Popovers</strong>, the option to use &#8220;natural&#8221; scrolling the way you do on the iPad, iOS-style invisible scroll bars, <strong>iCloud</strong> support, full-screen applications, and even some great new enhancements for developers using Objective-C.</p>
<p>So what is Apple planning to do with Mac OS X <em>Mountain Lion</em>? According to the information I can find publicly, here are some of the highlights:</p>
<ul>
<li><strong>Game Center</strong> &#8211; Apple&#8217;s game service that provides everything from matchmaking to leader boards, achievements, and even in-game multiplayer voice chat is coming to the Mac. This also means that developers writing games for the Mac will be able to participate in all that amazing goodness that iOS developers have been enjoying since iOS 4.1.</li>
<li><strong>iCloud</strong> &#8211; I don&#8217;t really know all the details here only that iCloud is even more integrated into the OS now and I&#8217;m assuming the developer experience around iCloud is getting better. I&#8217;m actually <em>hoping</em> that experience gets better because writing iCloud code on Lion is a pain in the ass.</li>
<li><strong>Sharing</strong> &#8211; More iOS goodness comes to the Mac with sharing &#8220;sheets&#8221;. Every application on Mountain Lion now gets a little sharing icon that uses sharing services, allowing you to share whatever you&#8217;re looking at in the application with your buddies via e-mail or whatever other services are registered on the Mac, including <strong>Twitter</strong>. I would imagine that it wouldn&#8217;t take much work, assuming the sharing APIs are good, to add other sharing targets like Facebook, Dropbox, LinkedIn, etc to your Mac &#8211; turning it into just as much of a social hub as your phone.</li>
<li><strong>Twitter</strong> - Twitter is a first-class citizen on the Mac just like it became first-class on iOS 5<em>. </em>This means that Mountain Lion users can tweet from pretty much anywhere and using the &#8220;sharing&#8221; services, they can share pretty much whatever they&#8217;re working on in any application (that supports it) via Twitter. Not only is twitter a first-class citizen, but applications can send Tweets on behalf of their users <em>without any extra work</em>. Twitter appears to be accessible in API form to developers without them having to figure out which of the 10 open-source Objective-C twitter libraries they want to shoehorn into their app. This is fantastic news for developers and I hope we get similar integration possibilities with Facebook, Dropbox, etc via Sharing &#8220;sheet&#8221; APIs.</li>
<li><strong>Notifications</strong> - In what looks to be <em>very</em> similar to the notification center on iOS 5, Apple now has a unified display of messages that are pertinent to the user, including IMs, iMessages (also now a fully integrated part of Mountain Lion), and application-level notifications. In classic Apple style, they are aiming to push popular 3rd parties out of this market with their 1st party offering. Applications like <strong>Growl</strong> may find it hard to compete with the unified interface, but time will tell how the 1st-vs-3rd party battles are settled.</li>
<li><strong>Gatekeeper</strong> - Again I don&#8217;t know all the details, but this feature aims to make your application more secure and, more importantly, provides developers with a secure way of distributing <em>verified, signed</em> applications <em>outside the app store</em>. For most developers, the App Store is absolutely the best way to go. But for some applications, it makes no sense to put in the app store and many people don&#8217;t need Apple&#8217;s distribution channel and so aren&#8217;t comfortable sharing 30% of their profit with the company. Gatekeeper and Developer IDs and signing give developers a way of distributing applications that users can feel comfortable downloading, installing, and using.</li>
<li><strong>64-Bit</strong> &#8211; You simply cannot run Mountain Lion on a 32-bit machine. The kernel is 64-bit and an entire host of 32-bit &#8220;wrappers&#8221; are missing in Mountain Lion, further drawing a line in the sand against 32-bit apps. If only some other software giant whose name starts with <strong>M</strong> that makes an operating system would also draw a similar line. In words from one of my favorite movies of all time (Zombieland), &#8220;It&#8217;s time to nut up or shut up.&#8221;</li>
<li><strong>SSO</strong> &#8211; In order to support seamless sharing and such, there appears to be some kind of single sign-on facility in OS X much like Windows has been allowing you to link your &#8220;LiveID&#8221; to your user account for quite some time &#8230; only with the Twitter integration I would imagine Apple&#8217;s SSO allows for more than just Apple ID storage.</li>
</ul>
<p>All in all Mountain Lion is looking pretty promising. Again, there&#8217;s absolutely nothing groundbreaking in here, but starting with <strong>Lion</strong> and continuing with <strong>Mountain Lion</strong>, it appears that Mac developers are finally getting access to the same amount of lovin&#8217; that the iOS developers have been enjoying since iOS 4.</p>
<img src="http://feeds.feedburner.com/~r/KotanCode/~4/jIfbUVrGaCU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.kotancode.com/2012/02/17/ios-mountain-lion-convergence-mac/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.kotancode.com/2012/02/17/ios-mountain-lion-convergence-mac/</feedburner:origLink></item>
		<item>
		<title>ScalaMUD – Consuming Java from Scala and NLP Tagging</title>
		<link>http://feedproxy.google.com/~r/KotanCode/~3/XiNLaCYBZi8/</link>
		<comments>http://www.kotancode.com/2012/02/15/scalamud-scala-java-nlp/#comments</comments>
		<pubDate>Wed, 15 Feb 2012 12:40:38 +0000</pubDate>
		<dc:creator>Kevin Hoffman</dc:creator>
				<category><![CDATA[Languages]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[akka]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[language]]></category>
		<category><![CDATA[mud]]></category>
		<category><![CDATA[nlp]]></category>
		<category><![CDATA[parsers]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[ScalaMUD]]></category>

		<guid isPermaLink="false">http://www.kotancode.com/?p=428</guid>
		<description><![CDATA[Last night I upgraded ScalaMUD&#8217;s POM file to point to the recently-available Akka 2.0-RC1. I was previously using M3 an was happy to note that all of my Akka 2.0 code continued working just fine without change from M3 to RC1. If the Akka RC is like most other RCs then there should be no [...]]]></description>
			<content:encoded><![CDATA[<p>Last night I upgraded ScalaMUD&#8217;s POM file to point to the recently-available Akka 2.0-RC1. I was previously using M3 an was happy to note that all of my Akka 2.0 code continued working just fine without change from M3 to RC1. If the Akka RC is like most other RCs then there should be no further API changes, only fixes and tightening.</p>
<p>While I had the MUD code open I decided to start working on the problem of accepting player input. Sure, I have a socket reader that accepts text from players but what does one do with this text?</p>
<p>In the old days, I would&#8217;ve tokenized the string. By tokenized here I mean just splitting it blindly on spaces. Then I would have considered the first word in the array to be the verb and then dispatched the remaining parameters to some function in the MUD code that knows how to respond to that verb. For example, if I typed <em>kill dragon</em> then I would&#8217;ve tagged <em>kill</em> as the <strong>verb</strong> and <em>dragon</em> as the &#8220;rest&#8221;. This would have eventually found its way to some <em>kill()</em> method on a player that takes an array of strings as parameters.</p>
<p>Thankfully this isn&#8217;t the old days.</p>
<p>Instead what I did was declare a Maven dependency on the <a href="http://nlp.stanford.edu/software/tagger.shtml" target="_blank">Stanford NLP (Natural Language Processing) project</a>. To be specific, I wanted to use the Stanford non-linear Parts of Speech tagger. Why should I deal with parsing strings in a dumb way when someone else has spent <em>years</em> creating a powerful, well-trained NLP engine that can tag every sentence my player types with parts of speech?</p>
<p>This way, instead of relying on forcing players to type in pidgin dialects (e.g. <em>kill dragon</em> or <em>cast spell </em>or <em>move north</em>) I can let them type complete English sentences (if they want). I will then tag those sentences with the appropriate parts of speech and infer what they wanted to do from that.</p>
<p>I want this parsing to take place in the background. Once the player&#8217;s sentence has been <em>enriched</em> with parts of speech, I want to send the enriched sentence back to whatever typed it so that the command can be dispatched. To do this, I created a new Actor called <strong>Commander</strong>:</p>
<pre class="brush: scala; title: ; notranslate">
package com.kotancode.scalamud.core

import akka.actor._
import akka.routing._

import com.kotancode.scalamud.core.lang.EnrichedWord
import java.util.ArrayList
import edu.stanford.nlp.ling.Sentence
import edu.stanford.nlp.ling.TaggedWord
import edu.stanford.nlp.ling.HasWord
import edu.stanford.nlp.tagger.maxent.MaxentTagger
import scala.collection.JavaConverters._

class Commander extends Actor {
	def receive = {
		case s:String =&gt; {
			val words = s.split(&quot; &quot;);
			val wordList = new java.util.ArrayList[String]();
			for (elem &lt;- words) wordList.add(elem)
		    val sentence = Sentence.toWordList(wordList);
		    val taggedSentence = Commander.tagger.tagSentence(sentence).asScala.toList

			var enrichedWords = new ArrayList[EnrichedWord]
		    for (tw : TaggedWord &lt;- taggedSentence) {
		//		println(tw.value + &quot;/&quot; + tw.tag)
				val ew = EnrichedWord(tw)
				println(ew)
				enrichedWords.add(ew)
			}
	}
  }
}

object Commander {
	val tagger = new MaxentTagger(&quot;models/english-bidirectional-distsim.tagger&quot;)
}
</pre>
<p>At this point I&#8217;m just building the array of enriched words and I&#8217;m not actually sending the command back to the player (I&#8217;ll do that tonight or tomorrow, time permitting .. as always, you can check out the <a href="https://github.com/kotancode/ScalaMud" target="_blank">GitHub repo</a> for the latest changes to the MUD). One of the interesting bits here is how I&#8217;m using a Java library from Scala. This is usually a pretty painless task but sometimes there are issues. In this case, the Stanford NLP library class <strong>Sentence</strong> has a bunch of overloads for the <strong>toWordList</strong> method. Java knows how to pick which overload but Scala doesn&#8217;t if I just use type inference and default Scala types. To get it to pick the right <strong>toWordList</strong> method I had to manually construct an <strong>ArrayList[String]</strong> because passing an <strong>Array[String]</strong> doesn&#8217;t let Scala know which overload to pick. It&#8217;s a little annoying but if I can keep the Scala-&gt;Java bridge points like this minimal then it&#8217;s not bad.</p>
<p>The flip side of this is that I&#8217;m getting back a regular Java array list in response to <strong>toWordList</strong>, which doesn&#8217;t support pretty Scala-native iteration because it doesn&#8217;t contain a <strong>foreach</strong> method, which is the underpinning that supports all the syntactic sugar around iteration. To deal with that, I imported the Java converters package implicits so that I could get the <strong>asScala</strong> function, which lets me call <strong>toList</strong>, which gives me a nice Scala list that I can use for easy iteration.</p>
<p>Here&#8217;s some sample output when I connect to the MUD and enter a sample sentence, which is then tokenized and tagged with parts of speech:</p>
<pre>[EnrichedWord: word=attack, tag=VB, pos=Verb]
[EnrichedWord: word=the, tag=DT, pos=DontCare]
[EnrichedWord: word=green, tag=JJ, pos=Adjective]
[EnrichedWord: word=dragon, tag=NN, pos=Noun]
[EnrichedWord: word=with, tag=IN, pos=DontCare]
[EnrichedWord: word=the, tag=DT, pos=DontCare]
[EnrichedWord: word=yellow, tag=JJ, pos=Adjective]
[EnrichedWord: word=sword, tag=NN, pos=Noun]</pre>
<p>The real goal here is that I will be taking the tagged nouns in the sentence and scanning through the player&#8217;s inventory and the environment in which the player stands for objects which have names that match the nouns and then using adjectives to disambiguate them if collisions occur. That way, when I type &#8220;kick blue bottle&#8221; I will be able to scan the surroundings for objects called &#8220;bottle&#8221; and if I find more than one, I&#8217;ll only gather up the ones that are blue.</p>
<p>In case you&#8217;re wondering what the <strong>EnrichedWord</strong> class looks like, which has some helper code that identifies only the parts of speech I care about, here it is:</p>
<pre class="brush: scala; title: ; notranslate">
package com.kotancode.scalamud.core.lang

import edu.stanford.nlp.ling.TaggedWord

case class PartOfSpeech
case object Noun extends PartOfSpeech
case object Verb extends PartOfSpeech
case object Adjective extends PartOfSpeech
case object DontCare extends PartOfSpeech

class EnrichedWord(value:String, tag:String, val pos:PartOfSpeech) extends TaggedWord(value, tag) {

	override def toString = &quot;[EnrichedWord: word=&quot; + value +&quot;, tag=&quot; + tag + &quot;, pos=&quot; + pos + &quot;]&quot;
}

object EnrichedWord {
	def apply(hw: TaggedWord) = {
		val ew = new EnrichedWord(hw.value, hw.tag, rootTypeOf(hw.tag))
		ew
	}

	def rootTypeOf(s:String) = {
		s match {
			case &quot;VB&quot; | &quot;VBD&quot; | &quot;VBG&quot; | &quot;VBN&quot; | &quot;VBP&quot; | &quot;VBZ&quot; =&gt; Verb
			case  &quot;NN&quot; | &quot;NNS&quot; | &quot;NNP&quot; | &quot;NNPS&quot; =&gt; Noun
			case &quot;JJ&quot; | &quot;JJR&quot; | &quot;JJS&quot; =&gt; Adjective
			case _ =&gt; DontCare
		}
	}
}
</pre>
<p>Note that the <strong>EnrichedWord</strong> Scala class inherits from the Stanford <strong>TaggedWord</strong> Java class.</p>
<p>I really, <em>really</em>, love the syntax of the string pattern matcher I use to obtain the POS root (adjective, verb, noun, don&#8217;t care) from the Penn Treebank Tags that are used by the Stanford NLP POS tagger.</p>
<p>The takeaway I got from this exercise is further reinforcement of my rule to never re-invent the wheel because there are wheel experts out there who have dedicated their lives and careers to building wheels more awesome than I could ever hope to build. Hence I declare a Maven dependency on the NLP library and in a single night, I&#8217;ve got a MUD that can <em>intelligently</em> POS-tag player sentences which I can then use to identify potential targets of player commands. In addition, I don&#8217;t have to create a pidgin dialect for interacting with the MUD. English works and the MUD should be able to deal with &#8220;<em>I kill the dragon with the blue sword because I am the shizzle&#8221;</em> with the same ease as &#8220;<em>kill dragon with sword&#8221;</em>.</p>
<img src="http://feeds.feedburner.com/~r/KotanCode/~4/XiNLaCYBZi8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.kotancode.com/2012/02/15/scalamud-scala-java-nlp/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://www.kotancode.com/2012/02/15/scalamud-scala-java-nlp/</feedburner:origLink></item>
		<item>
		<title>Regular Expressions and Parsing in Scala</title>
		<link>http://feedproxy.google.com/~r/KotanCode/~3/O_3BFlQIuZg/</link>
		<comments>http://www.kotancode.com/2012/02/10/scala-regex/#comments</comments>
		<pubDate>Fri, 10 Feb 2012 15:11:56 +0000</pubDate>
		<dc:creator>Kevin Hoffman</dc:creator>
				<category><![CDATA[Languages]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[parsing]]></category>
		<category><![CDATA[pattern matching]]></category>
		<category><![CDATA[regex]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://www.kotancode.com/?p=426</guid>
		<description><![CDATA[Last night I was messing around with some code and I wanted to rip a couple of pieces of information out of a free-from string. This is typically where people reach for regular expressions. Not me, though. No, my experience with regular expression support and parsing in other languages like C# and Java has left [...]]]></description>
			<content:encoded><![CDATA[<p>Last night I was messing around with some code and I wanted to rip a couple of pieces of information out of a free-from string. This is typically where people reach for regular expressions. Not me, though.</p>
<p>No, my experience with regular expression support and parsing in other languages like C# and Java has left a terrible taste in my mouth. I hate it. When I want to parse stuff, I want to use pattern matching and rich syntax like I can get from languages like F# or Scala.</p>
<p>This made me wonder if Scala didn&#8217;t make regex parsing easier. Turns out, it makes it brain-dead simple with the clever use of the concept of an <em>unapply</em>. The same capability that makes Scala so good at constructing, zipping, and traversing list structures also makes it just as good at cracking apart structures into their component parts.</p>
<p>As a sample, I created a simple string in Scala and then put the &#8220;.r&#8221; postfix on it, turning it into a regular expression:</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; val zombieLog = &quot;&quot;&quot;(d\+) zombies spotted in (\w+).&quot;&quot;&quot;.r
</pre>
<p>This created a regular expression with two groups. If you&#8217;re used to doing this kind of thing in Java or C# then you&#8217;re probably thinking that you now need to write 10 lines of code to set up the regex compiler, call some method to feed the string into the regex compiler, then access groups by numeric, 0-based indexes.</p>
<p>Fortunately, this is Scala and more often than not, things suck less in Scalaville.</p>
<p>First, I&#8217;ll create an input string that I want to crack apart with my regex:</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; val inputText = &quot;200 zombies spotted in Mexico.&quot;
</pre>
<p>Now I&#8217;ll use unapply and syntactic sugar and Scala goodness to pull out the right values:</p>
<pre class="brush: java; title: ; notranslate">
scala&gt; val zombieLog(zombieCount, location) = inputText // UNAPPLY magic
zombieCount: String = 200
location: String = Mexico
</pre>
<p>And that&#8217;s it, Bob&#8217;s your uncle. With the plethora of online regular expression builders available, it should only take you a few minutes to create the regex you need and slap it into your Scala code.</p>
<img src="http://feeds.feedburner.com/~r/KotanCode/~4/O_3BFlQIuZg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.kotancode.com/2012/02/10/scala-regex/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.kotancode.com/2012/02/10/scala-regex/</feedburner:origLink></item>
		<item>
		<title>Scala Companion Objects</title>
		<link>http://feedproxy.google.com/~r/KotanCode/~3/uBVbdw7xb20/</link>
		<comments>http://www.kotancode.com/2012/02/09/scala-companion-objects/#comments</comments>
		<pubDate>Thu, 09 Feb 2012 18:02:20 +0000</pubDate>
		<dc:creator>Kevin Hoffman</dc:creator>
				<category><![CDATA[Languages]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[companion objects]]></category>
		<category><![CDATA[factory]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[scala]]></category>

		<guid isPermaLink="false">http://www.kotancode.com/?p=420</guid>
		<description><![CDATA[In a single sentence, a Scala companion object is an object with the same name as a companion class in the same file that has access to all of that class&#8217; members, including the private ones. At first, the power and utility of these companion objects wasn&#8217;t really all that clear to me but then I [...]]]></description>
			<content:encoded><![CDATA[<p>In a single sentence, a Scala companion object is an object with the same name as a companion class <em>in the same file</em> that has access to all of that class&#8217; members, including the private ones.</p>
<p>At first, the power and utility of these companion objects wasn&#8217;t really all that clear to me but then I started finding myself using them more and more to the point where I am pretty sure I couldn&#8217;t write a Scala app of any decent size without using them.</p>
<p>Let&#8217;s take a look at one of the most common uses of a companion object as a place to put factory methods using the <strong>apply</strong> method:</p>
<pre class="brush: java; title: ; notranslate">
class BucketOSlime private (val slimeColor:String) {
    // Stuff goes here...
}
object BucketOSlime {
    def apply(color:String):BucketOSlime = new BucketOSlime(color)
}
</pre>
<p>With this code in place you can now create colorful buckets of slime with a constructor shortcut syntax that lets you leave off the word &#8220;new&#8221; entirely:</p>
<pre class="brush: java; title: ; notranslate">
val blueSlime = BucketOSlime(&quot;blue&quot;)
val whiteSlime = BucketOSlime(&quot;white&quot;)
</pre>
<p>The fun (and power) doesn&#8217;t stop here. You can use multiple apply methods or a single apply method with pattern matching to return different instances of the same abstract object:</p>
<pre class="brush: java; title: ; notranslate">
object BucketOSlime {
    def apply(color:String):BucketOSlime = {
        if (color == &quot;blue&quot;)
              new BlueBucketOSlime
        else
              new RegularBucketOSlime(color)
    }
}
</pre>
<p>There are a ton of other ways you can use companion objects. Another common one is to wrap implicits to upgrade or enrich a class (like I&#8217;ve done with my MUD recently) so that the implicit doesn&#8217;t need to be imported directly.</p>
<p>The more I use Scala, the more I thoroughly enjoy it. I still utterly despise when I see people overloading symbols everywhere so that Scala&#8217;s complexity approaches &#8220;write once confuse everywhere&#8221; status&#8230; but with discipline I still think developers can keep Scala syntax clean, concise, and eminently readable.</p>
<img src="http://feeds.feedburner.com/~r/KotanCode/~4/uBVbdw7xb20" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.kotancode.com/2012/02/09/scala-companion-objects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.kotancode.com/2012/02/09/scala-companion-objects/</feedburner:origLink></item>
		<item>
		<title>SAMS Teach Yourself Mac OS X Lion Programming in 24 Hours</title>
		<link>http://feedproxy.google.com/~r/KotanCode/~3/lqrQr-iSWIY/</link>
		<comments>http://www.kotancode.com/2012/02/06/sams-teach-yourself-mac-os-x-lion-programming-in-24-hours/#comments</comments>
		<pubDate>Mon, 06 Feb 2012 15:57:00 +0000</pubDate>
		<dc:creator>Kevin Hoffman</dc:creator>
				<category><![CDATA[Publications]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[apple]]></category>
		<category><![CDATA[books]]></category>
		<category><![CDATA[cocoa]]></category>
		<category><![CDATA[lion]]></category>
		<category><![CDATA[mac]]></category>
		<category><![CDATA[objective-c]]></category>
		<category><![CDATA[osx]]></category>
		<category><![CDATA[osxlion]]></category>
		<category><![CDATA[publications]]></category>
		<category><![CDATA[same]]></category>

		<guid isPermaLink="false">http://www.kotancode.com/?p=415</guid>
		<description><![CDATA[As some of you may know, I spent a tremendous amount of time and effort working on this book, which you can buy over here at Amazon.com. I am posting this blog post here to let people know that all of the revisions are done, all of the proofs have been approved and accepted, and [...]]]></description>
			<content:encoded><![CDATA[<p>As some of you may know, I spent a tremendous amount of time and effort working on this book, <a href="http://www.amazon.com/Sams-Teach-Yourself-Development-Hours/dp/0672335816/ref=sr_1_1?ie=UTF8&amp;qid=1328543572&amp;sr=8-1" target="_blank">which you can buy over here at Amazon.com</a>.</p>
<div id="attachment_418" class="wp-caption aligncenter" style="width: 160px"><a href="http://www.kotancode.com/wp-content/uploads/2012/02/styosxlion24_cover.jpg"><img class="size-thumbnail wp-image-418" title="Cover Art - SAMS Teach Yourself Mac OS X Lion Programming in 24 Hours" src="http://www.kotancode.com/wp-content/uploads/2012/02/styosxlion24_cover-150x150.jpg" alt="Cover Art - SAMS Teach Yourself Mac OS X Lion Programming in 24 Hours" width="150" height="150" /></a><p class="wp-caption-text">Cover Art - SAMS Teach Yourself Mac OS X Lion Programming in 24 Hours</p></div>
<p>I am posting this blog post here to let people know that all of the revisions are done, all of the proofs have been approved and accepted, and the only thing left to do for this book is to print it.</p>
<p>So now there is no excuse &#8211; go out and buy yourself a copy. Then buy one for your friends and your parents and your friends&#8217; parents.</p>
<p>I hope you enjoy reading the book and learning from it as much as I enjoyed writing it.</p>
<img src="http://feeds.feedburner.com/~r/KotanCode/~4/lqrQr-iSWIY" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.kotancode.com/2012/02/06/sams-teach-yourself-mac-os-x-lion-programming-in-24-hours/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.kotancode.com/2012/02/06/sams-teach-yourself-mac-os-x-lion-programming-in-24-hours/</feedburner:origLink></item>
		<item>
		<title>Adding State to Actors with the Pimp My Class Pattern</title>
		<link>http://feedproxy.google.com/~r/KotanCode/~3/PL0YVKwp5tU/</link>
		<comments>http://www.kotancode.com/2012/02/06/pimp-my-state-scalamud/#comments</comments>
		<pubDate>Mon, 06 Feb 2012 13:06:48 +0000</pubDate>
		<dc:creator>Kevin Hoffman</dc:creator>
				<category><![CDATA[Languages]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[actors]]></category>
		<category><![CDATA[akka]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[mud]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[pimpmyclass]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[ScalaMUD]]></category>
		<category><![CDATA[state]]></category>

		<guid isPermaLink="false">http://www.kotancode.com/?p=410</guid>
		<description><![CDATA[In my last blog post, I talked about how the new Akka 2.0 actor system hides an enforces the inaccessibility of the actual class of the underlying actor. For example, if you have a class called Zombie that is of type Actor, then when you use the actor system to start that actor, what you get [...]]]></description>
			<content:encoded><![CDATA[<p>In <a title="You spilled some OOP in my Actor System!" href="http://www.kotancode.com/2012/02/02/you-spilled-some-oop-in-my-actor-system/" target="_blank">my last blog post</a>, I talked about how the new Akka 2.0 actor system hides an enforces the inaccessibility of the actual class of the underlying actor. For example, if you have a class called <strong>Zombie</strong> that is of type <strong>Actor</strong>, then when you use the actor system to start that actor, what you get back is an <strong>ActorRef</strong>, and (without cheating), there is no way to typecast or otherwise gain access to the <strong>Zombie</strong> type from an instance of <strong>ActorRef</strong>. While it felt limiting, once I embraced the design principle that necessitated that enforcement, I understood.</p>
<p>That said, I am building a MUD here and I&#8217;m going to need state. My rooms need names, descriptions, and exits. My NPCs are going to need combat stats and inventories, my players are going to need names, descriptions, races, genders, etc. This is all basic stuff but &#8211; if I can&#8217;t get to a game object reference from an <strong>ActorRef</strong>, how am I going to get at their internal state?</p>
<p>Easy! Don&#8217;t use <em>internal</em> state.</p>
<p>Remembering back to my first post where I upgraded my old Scala MUD to use Akka actors, I noted that every actor in a system has a <em>unique</em> path string that denotes its position within a hierarchy of supervisory actors much like the way supervisors and processes exist in an Erlang system. That gave me the idea to store the state for my actors in a big in-memory hash (which I could then upgrade to some kind of distributed or CouchDB-type store later).</p>
<p>With that problem solved, the only real problem now was that my <strong>ActorRef</strong> instances didn&#8217;t have concrete properties. One of my favorite features of Scala, which is also used in building DSLs, is the <em>pimp my class</em> or <em>pimp my library</em> pattern. This works very much like class extensions in C#. I can create a class that encapsulates or <em>enriches</em> an underlying class type by providing methods that operate on or with that class. In my case, I wanted strongly typed accessors like <strong>name</strong> and <strong>description</strong> that actually deferred the backing store to this singleton, in-memory hash.</p>
<p>Here&#8217;s my scala file that contains an <strong>Implicits</strong> object that <em>enriches</em> the <strong>ActorRef</strong> type with the wrapper class and the wrapper class provides a getter and setter for <strong>name</strong>.</p>
<pre class="brush: java; title: ; notranslate">
package com.kotancode.scalamud.core

import akka.actor.ActorRef
import scala.collection.mutable.{Map,
    SynchronizedMap, HashMap}

object Implicits {
	implicit def enrichActorRef(value: ActorRef) = new WrappedActorRef(value)
}

/*
 * Singleton containing a hash map keyed on the Actor Ref path
 * which contains additional hash maps.
 * There is one hash map for every actorref that needs state
 */
object StateMap {

   // Creates a thread-safe hash map
   def makeMap: Map[String, HashMap[String,String]] = {
       new HashMap[String, HashMap[String,String]] with
           SynchronizedMap[String, HashMap[String,String]]
   }

   private var stateMap = makeMap

   def getState(key:String):HashMap[String,String] = {
   	 if (!stateMap.contains(key))
	     stateMap.put(key, new HashMap[String,String])
	 stateMap(key)
   }

   def setState(key:String, propertyName:String, value:String) = {
		var state: HashMap[String,String] = null
		val result = stateMap.get(key)
		result match {
			case Some(x) =&gt; state = x
			case None =&gt; state = new HashMap[String,String]
		}
		state.put(propertyName, value)
		stateMap.put(key, state)
   }
}

class WrappedActorRef(val actorRef: ActorRef) {

	def name:String = StateMap.getState(actorRef.path.toString)(&quot;name&quot;)
	def name_=(value:String) { StateMap.setState(actorRef.path.toString, &quot;name&quot;, value) }
}
</pre>
<p>An obvious refactoring opportunity here would be to move the <strong>StateMap</strong> class out to its own separate Scala file but I&#8217;ve always been a huge fan of the agile process of getting something working first and refactoring afterward.</p>
<p>Now, to use my newly enhanced ActorRef (with state) class all I have to do is add the following import</p>
<pre class="brush: java; title: ; notranslate">
import com.kotancode.scalamud.core.Implicits._
</pre>
<p>To the top of my Scala file and below anywhere the type <strong>ActorRef</strong> is known, I can read and write the <strong>name</strong> property, as shown here:</p>
<pre class="brush: java; title: ; notranslate">
	private def handlePlayerLogin(player:ActorRef) = {
		println(&quot;Player logged in: &quot; + player)
		allPlayers ::= player
		for (p: ActorRef &lt;- allPlayers) {
			p ! TextMessage(player.name + &quot; logged in.&quot;)
	    }
</pre>
<p>Because <strong>ActorRef</strong> has been pimped to use the external state provider, I can use <strong>player.name</strong> in my code and it works!</p>
<img src="http://feeds.feedburner.com/~r/KotanCode/~4/PL0YVKwp5tU" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.kotancode.com/2012/02/06/pimp-my-state-scalamud/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.kotancode.com/2012/02/06/pimp-my-state-scalamud/</feedburner:origLink></item>
		<item>
		<title>You spilled some OOP in my Actor System!</title>
		<link>http://feedproxy.google.com/~r/KotanCode/~3/F8m6ElCHfBM/</link>
		<comments>http://www.kotancode.com/2012/02/02/you-spilled-some-oop-in-my-actor-system/#comments</comments>
		<pubDate>Fri, 03 Feb 2012 02:11:30 +0000</pubDate>
		<dc:creator>Kevin Hoffman</dc:creator>
				<category><![CDATA[Languages]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[actors]]></category>
		<category><![CDATA[akka]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[pop]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[typesafe]]></category>

		<guid isPermaLink="false">http://www.kotancode.com/?p=407</guid>
		<description><![CDATA[Lately I&#8217;ve been doing a lot of experimenting and playing with Scala and Akka. I&#8217;ve been building a MUD to give me a goal as I learn the language, the framework, and the intricacies involved. So far I&#8217;ve been focused mostly on syntax and learning what idiomatic Scala looks like, how to create and use [...]]]></description>
			<content:encoded><![CDATA[<p>Lately I&#8217;ve been doing a lot of experimenting and playing with Scala and Akka. I&#8217;ve been building a MUD to give me a goal as I learn the language, the framework, and the intricacies involved.</p>
<p>So far I&#8217;ve been focused mostly on syntax and learning what idiomatic Scala looks like, how to create and use Akka actors, and so on. It wasn&#8217;t until the other night that I started thinking about design and philosophy. This mini-revelation came about when I spent hours trying to find a way to get the actual type from underneath an <strong>ActorRef</strong>.</p>
<p>I was using <strong>context.actorOf()</strong> to create actors, as one should with Akka 2.0. So I might be creating and starting actors for rooms, monsters, or living room tables &#8211; anything that I thought might be instructive to mess around with. This is when I noticed that once you create an <strong>ActorRef</strong> by adding your actor to the actor system (either via <strong>system.actorOf</strong> or <strong>context.actorOf</strong>) you can&#8217;t get at the actual class underneath. <em>All</em> you can do is interact with it like an actor-shaped black box by sending and receiving messages.</p>
<p>In other words, let&#8217;s say I&#8217;ve got a class called <strong>Zombie</strong> that is an actor that I&#8217;ve added to the actor system. The <strong>Zombie</strong> has properties like <strong>name</strong>, <strong>eatingSpeed</strong>, and <strong>percentLivingTissueRemaining</strong>. With regular Scala actors, I would&#8217;ve been able to mix and match classic OOP-style programming with actor-style programming:</p>
<pre class="brush: java; title: ; notranslate">
println(tehZombie.name)
tehZombie.percentLivingTissueRemaining = 12
tehZombie ! FeedUpon(randomVictim)
</pre>
<p>At first this might look nice and appealing, but there&#8217;s something insidious happening here. First, our code has access to the internal state of <strong>tehZombie</strong> for both reading and writing. Secondly, we can send actor-style messages to <strong>tehZombie. </strong>Back during my first attempt at a MUD using regular Scala actors, I <em>regularly</em> abused this capacity &#8211; reading public fields from instances of actors all the while sending them messages.</p>
<p>One main purpose of an actor system is to take the complexity away of multi-threaded access to shared state and business logic. If we have one actor able to access another actor using standard OOP-style member-access patterns, we&#8217;ve basically <em>ruined</em> all of the advantages we&#8217;re getting from the actor system to begin with because <em>access to public state on an object is not inherently thread-safe</em>.</p>
<p>If we change internal state on an Akka actor in response to a message, <em>we are guaranteed that such a state change is thread-safe</em>. Not only is it thread-safe, it&#8217;s single-threaded because the actor&#8217;s inbox is being processed by that actor&#8217;s thread (or thread pool) <em>and no one else</em>.</p>
<p>So what does this mean? It means that, <em>within the context of an actor system</em>, <strong>public state and OOP-style member access is <em>BAD</em></strong>.</p>
<p>Unfortunately, what this means for my MUD is that I&#8217;ve got some refactoring to do because I noticed that I&#8217;ve been cheating and I passed around a reference to <strong><em>this</em></strong> to another actor &#8211; which gave that actor &#8220;unsafe&#8221; access to public members of my class. What I really should be doing is making sure that <em>nothing</em> on my actors is exposed publicly and I should be aiming for a <em>message pure</em> environment where <em>everything</em> works as though actors are black boxes that just receive messages, do what they need to do, and send back out messages to other actors within the system.</p>
<p>Akka 2.0 enforces an awful lot of this by suppressing access to <em>this</em> from other actors (I cheated&#8230; bad, bad, Kevin). Hopefully within a few days (after the Giants win the Super Bowl) I will have some refactoring checked into the Github repo that hopefully has a fully functioning system that is clean, <em>message pure</em>, and exposes <em>no unsafe members</em>.</p>
<p>Wish me luck <img src='http://www.kotancode.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<img src="http://feeds.feedburner.com/~r/KotanCode/~4/F8m6ElCHfBM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.kotancode.com/2012/02/02/you-spilled-some-oop-in-my-actor-system/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.kotancode.com/2012/02/02/you-spilled-some-oop-in-my-actor-system/</feedburner:origLink></item>
		<item>
		<title>ScalaMUD – Updated to Akka 2.0-M3</title>
		<link>http://feedproxy.google.com/~r/KotanCode/~3/Ld3yNY2_iQM/</link>
		<comments>http://www.kotancode.com/2012/01/30/scalamud-updated-to-akka-2-0-m3/#comments</comments>
		<pubDate>Tue, 31 Jan 2012 01:40:31 +0000</pubDate>
		<dc:creator>Kevin Hoffman</dc:creator>
				<category><![CDATA[Languages]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[actors]]></category>
		<category><![CDATA[akka]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jvm]]></category>
		<category><![CDATA[mud]]></category>
		<category><![CDATA[scala]]></category>
		<category><![CDATA[ScalaMUD]]></category>
		<category><![CDATA[typesafe]]></category>

		<guid isPermaLink="false">http://www.kotancode.com/?p=401</guid>
		<description><![CDATA[Tonight I decided to dig back into my tiny little MUD sample (which doesn&#8217;t have much in common with a real MUD at this point&#8230; but that will change soon) and upgrade it to work with the current milestone of Akka, 2.0-M3 which came out just last week from what I can tell. There is [...]]]></description>
			<content:encoded><![CDATA[<p>Tonight I decided to dig back into my tiny little MUD sample (which doesn&#8217;t have much in common with a real MUD at this point&#8230; but that will change soon) and upgrade it to work with the current milestone of Akka, 2.0-M3 which came out just last week from what I can tell.</p>
<p>There is actually quite a bit of difference in complexity and power between Akka 1.3 and Akka 2.0. There&#8217;s a <a href="http://scala.micronauticsresearch.com/akka-2-0/akka-1-2--2-0" target="_blank">detailed blog post here</a> that covers some details on the breaking changes between 1.2/1.3 and 2.0.</p>
<p>The biggest thing that concerns me is that Akka 2.0 has this concept of an <em>actor system</em>, which is really a tree-like hierarchy of actors. Some actors act in a supervisory capacity over other child actors and this tree is query able at runtime. If this sounds like Erlang&#8217;s supervisor process system to you that&#8217;s no accident&#8230; the philosophy guiding the development of Akka 2.0&#8242;s actor system is very Erlang-ish.</p>
<p>So when I create my top-level Game singleton object, I now need to create an instance of an <em>Actor System</em> and fire up a <em>top level actor</em> (I can have multiple top-level actors):</p>
<pre class="brush: java; title: ; notranslate">
package com.kotancode.scalamud

import akka.actor._
import akka.routing._

/*
 * Root-level Game singleton
 * Creates the Akka Actor System for all subsequent game objects
 */
object Game extends App {
	val system = ActorSystem(&quot;ScalaMUD&quot;)
	val server = system.actorOf(Props(new GameServer()), &quot;server&quot;)
	println(&quot;System Starting&quot;)
	server ! ServerStart()
}
</pre>
<p>Note here the use of <strong>system.actorOf</strong>. If I want to create a subordinate (child) actor within the context of the parent actor doing the creation, then I would use <strong>context.actorOf</strong>. I can give each of my actors a unique name so that they have descriptive <em>path </em>names when they appear in the actor system tree.</p>
<p>So far I was happy with the upgrade and I didn&#8217;t have too much trouble. Then I got to the point where I was creating anonymous actors in order to execute my while loops for accepting sockets and reading input from a socket in the background&#8230; Akka 2.0 has <em>removed</em> the <strong>spawn { }</strong> syntax and replaced it with some severe limitations, namely you can no longer create anonymous actors that do not implement a <em>receive</em> method. This means the old <strong>spawn { // do something }</strong> construct is impossible, replaced with this snippet from my GameServer class:</p>
<pre class="brush: java; title: ; notranslate">
case s:ServerStart =&gt; {
	context.actorOf(Props(new Actor {
		def receive = {
			case ss:ServerStart =&gt; {
				startSocketListener
			}
		}
	})) ! s
</pre>
<p>If you&#8217;re thinking OMGWTFBBQ at this point, you&#8217;re not alone. Basically what I&#8217;m doing is creating an anonymous actor, defining a receive method that receives a specific message and does something in response to that message and then <em>sending a message to my anonymous actor</em>. This is actually the way the documentation tells you to spawn off asynchronous background tasks without using named actors.</p>
<p>Before you start the flame war here &#8211; it is worth taking a minute to think hard about the fact that <em>everything</em> that occurs asynchronously within Akka is supposed to be an asynchronous <em>event-driven, message-passing</em> construct. In short, if I was really anal about this, I would have spawned off an actor that reads from the input socket stream in its own private loop and I would have spawned off <em>another</em> actor that encapsulates the output writer. When the input reader has read a line, it should send a message indicating that a line has been read and when something needs to send text to a player, it should do so through its output writer actor.</p>
<p>At this point I&#8217;m not that anal and I don&#8217;t need that level of complexity, so I&#8217;m leaving it out. I only mention this alternative to ease the pain of the new way of doing anonymous actors.</p>
<p>In short, I did get the MUD running on Akka 2.0-M3 and, while a little put off by the anonymous actor syntax, I understand its need and I applaud the type safe people for forcing actors to receive messages.</p>
<p>If you want to follow the code for the MUD as I continue working on it, check out my <a href="https://github.com/kotancode/ScalaMud" target="_blank">GitHub repo</a>.</p>
<img src="http://feeds.feedburner.com/~r/KotanCode/~4/Ld3yNY2_iQM" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.kotancode.com/2012/01/30/scalamud-updated-to-akka-2-0-m3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.kotancode.com/2012/01/30/scalamud-updated-to-akka-2-0-m3/</feedburner:origLink></item>
	</channel>
</rss>

