Skip to content

Commit

Permalink
First commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Apress committed Oct 14, 2016
0 parents commit 78d5eb7
Show file tree
Hide file tree
Showing 35 changed files with 1,714 additions and 0 deletions.
Binary file added 4407.pdf
Binary file not shown.
Binary file added 4408.pdf
Binary file not shown.
Binary file added 9781430219897.jpg
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@@ -0,0 +1 @@
println("Hello World!")
@@ -0,0 +1,2 @@
for {i <- 1 to 10}
println(i)
@@ -0,0 +1,3 @@
for {i <- 1 to 10
j <- 1 to 10}
println(i * j)
21 changes: 21 additions & 0 deletions Beginning_Scala/beginning_scala_example_code/Chapter02/Sum.scala
@@ -0,0 +1,21 @@
import scala.io._

def toInt(in: String): Option[Int] =
try {
Some(Integer.parseInt(in.trim))
} catch {
case e: NumberFormatException => None
}

def sum(in: Seq[String]) = {
val ints = in.flatMap(s => toInt(s))
ints.foldLeft(0)((a, b) => a + b)
}

println("Enter some numbers and press ctrl-D (Unix/Mac) ctrl-C (Windows)")

val input = Source.fromInputStream(System.in)

val lines = input.getLines.collect

println("Sum "+sum(lines))
@@ -0,0 +1,55 @@
import java.util.concurrent.atomic.{AtomicReference => AtomR, AtomicLong}
import java.util.Random
import scala.collection.immutable.TreeHashMap

object Multics {
type MT = Map[String, Int]

val info: AtomR[MT] = new AtomR(TreeHashMap.empty)
val clashCnt = new AtomicLong

def main(argv: Array[String]) {
runThread {
repeatEvery(1000) {
println("Clash Count: "+clashCnt+" Total: "+
info.get.foldLeft(0)(_ + _._2))
} }

for (i <- 1 to 2000) runThread {
var cnt = 0
val ran = new Random
val name = "K"+i

doSet(info){old => old + (name -> 0)}
repeatEvery(ran.nextInt(100)) {
doSet(info){old => old + (name -> (old(name) + 1))}
cnt = cnt + 1
if (cnt != info.get()(name))
throw new Exception("Thread: "+name+" failed")
} }
}

def runThread(f: => Unit) =
(new Thread(new Runnable {def run(): Unit = f})).start

def doSet[T](atom: AtomR[T])(update: T => T) {
val old = atom.get
if (atom.compareAndSet(old, update(old))) ()
else {
clashCnt.incrementAndGet
doSet(atom)(update)
}
}

def repeatEvery(len: => Int)(body: => Unit): Unit = {
try {
while(true) {

Thread.sleep(len)
body
}
} catch {
case e => e.printStackTrace; System.exit(1)
}
}
}
16 changes: 16 additions & 0 deletions Beginning_Scala/beginning_scala_example_code/Chapter03/Roman.scala
@@ -0,0 +1,16 @@
def roman(in: List[Char]): Int = in match {
case 'I' :: 'V' :: rest => 4 + roman(rest)
case 'I' :: 'X' :: rest => 9 + roman(rest)
case 'I' :: rest => 1 + roman(rest)
case 'V' :: rest => 5 + roman(rest)
case 'X' :: 'L' :: rest => 40 + roman(rest)
case 'X' :: 'C' :: rest => 90 + roman(rest)
case 'X' :: rest => 10 + roman(rest)
case 'L' :: rest => 50 + roman(rest)
case 'C' :: 'D' :: rest => 400 + roman(rest)
case 'C' :: 'M' :: rest => 900 + roman(rest)
case 'C' :: rest => 100 + roman(rest)
case 'D' :: rest => 500 + roman(rest)
case 'M' :: rest => 1000 + roman(rest)
case _ => 0
}
@@ -0,0 +1,29 @@
import scala.xml._
import scala.xml.transform._

val removeIt = new RewriteRule {
override def transform(n: Node): NodeSeq = n match {
case e: Elem if (e \ "@instruction").text == "remove" => NodeSeq.Empty
case n => n
}
}

val addIt = new RewriteRule {
override def transform(n: Node): NodeSeq = n match {
case e: Elem if (e \ "@instruction").text == "add" =>
new Elem(e.prefix, e.label,
e.attributes.remove("instruction"),
e.scope,
transform(e.child) ++ <added>I added this</added> :_*)

case n => n
}
}

val xmlBooks =
<books instruction="update">
<book instruction="remove" name="book1" status=""/>
<book instruction="add" name="book2" status=""/>
</books>

println(new RuleTransformer(addIt, removeIt).transform(xmlBooks))
30 changes: 30 additions & 0 deletions Beginning_Scala/beginning_scala_example_code/Chapter04/Calc.scala
@@ -0,0 +1,30 @@
sealed trait Expr
case class Add(left: Expr, right: Expr) extends Expr
case class Mul(left: Expr, right: Expr) extends Expr
case class Val(value: Int) extends Expr
case class Var(name: String) extends Expr

object Calc {
def calc(expr: Expr, vars: Map[String, Int]): Int = expr match {
case Add(left, right) => calc(left, vars) + calc(right, vars)
case Mul(left, right) => calc(left, vars) * calc(right, vars)
case Val(v) => v
case Var(name) => vars(name)
}

def buildCalc(expr: Expr): Map[String, Int] => Int = expr match {
case Add(left, right) =>
val lf = buildCalc(left)
val rf = buildCalc(right)
m => lf(m) + rf(m)

case Mul(left, right) =>
val lf = buildCalc(left)
val rf = buildCalc(right)
m => lf(m) * rf(m)

case Val(v) => m => v

case Var(name) => m => m(name)
}
}
@@ -0,0 +1,16 @@
object Control {
def using[A <: {def close(): Unit}, B](param: A)(f: A => B): B =
try {
f(param)
} finally {
param.close()
}

import scala.collection.mutable.ListBuffer

def bmap[T](test: => Boolean)(block: => T): List[T] = {
val ret = new ListBuffer[T]
while(test) ret += block
ret.toList
}
}
@@ -0,0 +1,7 @@
object Fib {
def fibonacci(in: Int): Int = in match {
case 0 => 0
case 1 => 1
case n => fibonacci(n - 1) + fibonacci(n - 2)
}
}
@@ -0,0 +1,8 @@
object MyMules {
def myMules(name: String) = name match {
case "Elwood" | "Madeline" => Some("Cat")
case "Archer" => Some("Dog")
case "Pumpkin" | "Firetruck" => Some("Fish")
case _ => None
}
}
@@ -0,0 +1,40 @@
import scala.actors.Actor
import Actor._

case class Add(who: Actor)
case class Changed(what: AFoo, count: Int)
case object Access

class AFoo extends Actor {
private var listeners: List[Actor] = Nil
private var count = 0

def act = loop {
react {
case Add(who) => listeners = who :: listeners
case Access => access()
}
}

private def access() = {
notifyListeners
count += 1
}

private def notifyListeners =
listeners.foreach(a => a ! Changed(this, count))
}

class AFooListener(afoo: AFoo) extends Actor {
afoo ! Add(this)

def act = loop {
react {
case Changed(f, cnt) => changed(f, cnt)
}
}

def changed(eventFrom: AFoo, count: Int): Unit = {
if (count < 10) eventFrom ! Access
}
}
@@ -0,0 +1,21 @@
import scala.actors.Actor
import Actor._

case object GetInfo
case class Info(i: Map[String, Int])
case class SetInfo(n: String, v: Int)
case class Update(n: String, f: Option[Int] => Int)

object XAct1 extends Actor {
private var info: Map[String, Int] = Map()

def act = loop {
react {
case GetInfo => reply(Info(info))
case SetInfo(n, v) => info += n -> v
case Update(n, f) => info += n -> f(info.get(n))
}
}

this.start
}
@@ -0,0 +1,43 @@
import scala.actors.Actor
import Actor._

case object GetMessages
case class Messages(msg: List[String])
case class Remove(who: Actor)
case class Add(who: Actor)

object ChatServer3 extends Actor {
private var chats: List[String] = Nil
private var listeners: List[Actor] = Nil

def act = loop {
react(calcReact)
}

private def calcReact = {
val handle: PartialFunction[Any, Unit] = {
case s: String => chats = s :: chats
notifyListeners()

case GetMessages => reply(Messages(chats))
}

val mgt: PartialFunction[Any, Unit] =
if (chats.length < 3)
Map.empty
else {
case Add(who) => listeners = who :: listeners
who ! Messages(chats)

case Remove(who) => listeners -= who
}

handle orElse mgt
}

private def notifyListeners() {
listeners.foreach(a => a ! Messages(chats))
}

this.start()
}
@@ -0,0 +1,63 @@
import scala.actors.Actor
import Actor._

trait Buildable {
def handler: PartialFunction[Any, Unit] = Map.empty
}

case class Add(who: Actor)
case class Remove(who: Actor)

trait ListenerMgt extends Buildable {
private var listeners: List[Actor] = Nil

override def handler = super.handler orElse {
case Add(who) =>
listeners = who :: listeners
who ! updateMessage
case Remove(who) => listeners -= who
}

protected def updateListeners() {
val m = updateMessage
listeners.foreach(a => a ! m)
}

protected def updateMessage: Any
}

case object GetInfo

trait GetMgt extends Buildable {
override def handler = super.handler orElse {
case GetInfo => reply(updateMessage)
}

protected def updateMessage: Any
}

case class Messages(msgs: List[String])

object Chat extends Actor with ListenerMgt with GetMgt {
private var msgs: List[String] = Nil
def act = loop {
react(handler orElse {
case s: String => msgs ::= s
updateListeners()
})
}

protected def updateMessage = Messages(msgs)

this.start
}

class Listen extends Actor {
def act = loop {
react {
case Messages(m) => println("Got "+m)
}
}

this.start
}

0 comments on commit 78d5eb7

Please sign in to comment.