Skip to content

Instantly share code, notes, and snippets.

@dsugden
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dsugden/9155772 to your computer and use it in GitHub Desktop.
Save dsugden/9155772 to your computer and use it in GitHub Desktop.
More interesting OO State
case class Node(id:Int)
type SyncResponse = Either[String,List[Node]]
class Network {
var nodes: ListBuffer[Node] = ListBuffer.empty
val rng = scala.util.Random
/**
* Removes dead nodes
*/
def purge:SyncResponse = {
val x = rng.nextInt(3)
if((nodes.length % 5 == 1 )){ // a random error case
nodes = ListBuffer.empty
Left("************** PURGE KABOOM ****************")
}else {
val currentLength = nodes.length
if(currentLength > x){
val ret = nodes.toList.takeRight(x)
(1 to x).foreach(e => nodes.remove(nodes.length - e))
Right(ret)
}else Right(Nil)
}
}
/**
* Returns newly discovered nodes. A Side effect is that they are appended to nodes
*/
def discover:SyncResponse = {
val x = rng.nextInt(7)
// if(true){
if((nodes.length > 6 && (x % 4 == 1))){ // random error case
Left("************** DISCOVER KABOOM ****************")
}else {
(1 to x).foreach(e => nodes.append(new Node(e)))
Right(nodes.toList.takeRight(x))
}
}
override def toString = "Network["+nodes.length+"]"
def copy:Network = {
val networkCopy = new Network
networkCopy.nodes = nodes
networkCopy
}
}
// lets make a referentially transparent version
case class BetterNetwork(network:Network){
def resyncTransparent:(BetterNetwork,SyncResponse)={
val networkCopy = network.copy
val newlyDiscovered = networkCopy.discover
(BetterNetwork(networkCopy),newlyDiscovered)
}
def purgeTransparent:(BetterNetwork,SyncResponse)={
val networkCopy = network.copy
val newlypurged = networkCopy.purge
(BetterNetwork(networkCopy),newlypurged)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment