summaryrefslogtreecommitdiff
path: root/docs
diff options
context:
space:
mode:
authormichelou <michelou@epfl.ch>2006-02-22 17:54:31 +0000
committermichelou <michelou@epfl.ch>2006-02-22 17:54:31 +0000
commit96ae92e4f6f830a9a4e55768c3de0328a2a030ba (patch)
tree0b84d247c1693bf186787aaa8f0c75d89fea9be3 /docs
parentc1e184a3657d970a8fba6e3c7049f20a2e466bf0 (diff)
downloadscala-96ae92e4f6f830a9a4e55768c3de0328a2a030ba.tar.gz
scala-96ae92e4f6f830a9a4e55768c3de0328a2a030ba.tar.bz2
scala-96ae92e4f6f830a9a4e55768c3de0328a2a030ba.zip
adapted code to Scala 2 syntax in files src/exa...
adapted code to Scala 2 syntax in files src/examples/**/*.scala
Diffstat (limited to 'docs')
-rw-r--r--docs/examples/Parsers.scala38
-rw-r--r--docs/examples/auction.scala162
-rw-r--r--docs/examples/boundedbuffer.scala24
-rw-r--r--docs/examples/computeserver.scala26
-rw-r--r--docs/examples/futures.scala18
-rw-r--r--docs/examples/iterators.scala15
-rw-r--r--docs/examples/maps.scala109
-rw-r--r--docs/examples/oneplacebuffer.scala29
-rw-r--r--docs/examples/parsers1.scala100
-rw-r--r--docs/examples/parsers2.scala51
-rw-r--r--docs/examples/pilib/elasticBuffer.scala90
-rw-r--r--docs/examples/pilib/handover.scala134
-rw-r--r--docs/examples/pilib/mobilePhoneProtocol.scala146
-rw-r--r--docs/examples/pilib/piNat.scala48
-rw-r--r--docs/examples/pilib/rwlock.scala220
-rw-r--r--docs/examples/pilib/scheduler.scala107
-rw-r--r--docs/examples/pilib/semaphore.scala48
-rw-r--r--docs/examples/pilib/twoPlaceBuffer.scala48
-rw-r--r--docs/examples/sort.scala32
-rw-r--r--docs/examples/sort1.scala14
-rw-r--r--docs/examples/sort2.scala22
-rw-r--r--docs/examples/typeinf.scala109
22 files changed, 796 insertions, 794 deletions
diff --git a/docs/examples/Parsers.scala b/docs/examples/Parsers.scala
index 10512ab2fd..3d83d05fb9 100644
--- a/docs/examples/Parsers.scala
+++ b/docs/examples/Parsers.scala
@@ -1,8 +1,8 @@
-package examples;
+package examples
abstract class Parsers {
- type inputType;
+ type inputType
trait Parser[a] {
@@ -33,13 +33,13 @@ abstract class Parsers {
def ||| (p: => Parser[a]) = new Parser[a] {
def apply(in: inputType): Result = Parser.this.apply(in) match {
- case None => p(in)
- case s => s
+ case None => p(in)
+ case s => s
}
}
def &&& [b](p: => Parser[b]): Parser[b] =
- for (val _ <- this; val x <- p) yield x;
+ for (val _ <- this; val x <- p) yield x
}
def succeed[a](x: a) = new Parser[a] {
@@ -47,13 +47,13 @@ abstract class Parsers {
}
def rep[a](p: Parser[a]): Parser[List[a]] =
- rep1(p) ||| succeed(List());
+ rep1(p) ||| succeed(List())
def rep1[a](p: Parser[a]): Parser[List[a]] =
- for (val x <- p; val xs <- rep(p)) yield x :: xs;
+ for (val x <- p; val xs <- rep(p)) yield x :: xs
def opt[a](p: Parser[a]): Parser[List[a]] =
- (for (val x <- p) yield List(x)) ||| succeed(List());
+ (for (val x <- p) yield List(x)) ||| succeed(List())
}
class Tokenizer(in: Iterator[char], delimiters: String) extends Iterator[String] {
@@ -71,9 +71,9 @@ class Tokenizer(in: Iterator[char], delimiters: String) extends Iterator[String]
i < delimiters.length()
}
- def hasNext: boolean = ch != EOI;
+ def hasNext: boolean = ch != EOI
- private val buf = new StringBuffer;
+ private val buf = new StringBuffer
def next: String = {
while (ch <= ' ' && ch != EOI) nextChar();
@@ -81,8 +81,8 @@ class Tokenizer(in: Iterator[char], delimiters: String) extends Iterator[String]
else {
if (isDelimiter(ch)) ch.toString()
else {
- buf.setLength(0); buf append ch;
- while (ch > ' ' && ch != EOI && !isDelimiter(ch)) {
+ buf.setLength(0); buf append ch
+ while (ch > ' ' && ch != EOI && !isDelimiter(ch)) {
buf append ch; nextChar();
}
buf.toString()
@@ -91,18 +91,18 @@ class Tokenizer(in: Iterator[char], delimiters: String) extends Iterator[String]
}
}
-abstract class TokenParsers extends Parsers {
- type inputType = Stream[String];
+mixin class TokenParsers extends Parsers {
+ type inputType = Stream[String]
def nextToken() = new Parser[String] {
def apply(in: inputType): Result =
- if (in.isEmpty) None else Some(Pair(in.head, in.tail));
+ if (in.isEmpty) None else Some(Pair(in.head, in.tail))
}
}
-abstract class CharParsers extends Parsers {
- def any: Parser[char];
+mixin class CharParsers extends Parsers {
+ def any: Parser[char]
def chr(ch: char) =
- for (val c <- any; c == ch) yield c;
+ for (val c <- any; c == ch) yield c
def chr(p: char => boolean) =
- for (val c <- any; p(c)) yield c;
+ for (val c <- any; p(c)) yield c
}
diff --git a/docs/examples/auction.scala b/docs/examples/auction.scala
index c6ab223375..44f4318074 100644
--- a/docs/examples/auction.scala
+++ b/docs/examples/auction.scala
@@ -1,64 +1,64 @@
-package examples;
+package examples
-import java.util.Date;
-import scala.concurrent._;
+import java.util.Date
+import scala.concurrent._
/** A simple demonstrator program implementing an online auction service
* The example uses the actor abstraction defined in the API of
* package scala.concurrent.
*/
-trait AuctionMessage;
-case class
- Offer(bid: int, client: Actor), // make a bid
- Inquire(client: Actor) extends AuctionMessage; // inquire status
-
-trait AuctionReply;
-case class
- Status(asked: int, expiration: Date), // asked sum, expiration date
- BestOffer(), // yours is the best offer
- BeatenOffer(maxBid: int), // offer beaten by maxBid
- AuctionConcluded(seller: Actor, client: Actor), // auction concluded
- AuctionFailed(), // failed with no bids
- AuctionOver() extends AuctionReply; // bidding is closed
+trait AuctionMessage
+case class Offer(bid: int, client: Actor) extends AuctionMessage // make a bid
+case class Inquire(client: Actor) extends AuctionMessage // inquire status
+
+trait AuctionReply
+case class Status(asked: int, expiration: Date) // asked sum, expiration date
+ extends AuctionReply
+case class BestOffer() extends AuctionReply // yours is the best offer
+case class BeatenOffer(maxBid: int) extends AuctionReply // offer beaten by maxBid
+case class AuctionConcluded(seller: Actor, client: Actor) // auction concluded
+ extends AuctionReply
+case class AuctionFailed() extends AuctionReply // failed with no bids
+case class AuctionOver() extends AuctionReply // bidding is closed
class Auction(seller: Actor, minBid: int, closing: Date) extends Actor {
- val timeToShutdown = 3600000; // msec
- val bidIncrement = 10;
+ val timeToShutdown = 3600000 // msec
+ val bidIncrement = 10
override def run() = {
- var maxBid = minBid - bidIncrement;
- var maxBidder: Actor = null;
- var running = true;
+ var maxBid = minBid - bidIncrement
+ var maxBidder: Actor = null
+ var running = true
while (running) {
receiveWithin (closing.getTime() - new Date().getTime()) {
- case Offer(bid, client) =>
- if (bid >= maxBid + bidIncrement) {
+ case Offer(bid, client) =>
+ if (bid >= maxBid + bidIncrement) {
if (maxBid >= minBid)
- maxBidder send BeatenOffer(bid);
- maxBid = bid;
+ maxBidder send BeatenOffer(bid);
+ maxBid = bid
maxBidder = client;
client send BestOffer()
- } else {
+ }
+ else
client send BeatenOffer(maxBid)
- }
-
- case Inquire(client) =>
- client send Status(maxBid, closing)
-
- case TIMEOUT() =>
- if (maxBid >= minBid) {
- val reply = AuctionConcluded(seller, maxBidder);
- maxBidder send reply;
- seller send reply
- } else {
- seller send AuctionFailed()
+
+ case Inquire(client) =>
+ client send Status(maxBid, closing)
+
+ case TIMEOUT =>
+ if (maxBid >= minBid) {
+ val reply = AuctionConcluded(seller, maxBidder)
+ maxBidder send reply
+ seller send reply
}
+ else
+ seller send AuctionFailed()
receiveWithin(timeToShutdown) {
case Offer(_, client) => client send AuctionOver()
- case TIMEOUT() => running = false
+ case TIMEOUT => running = false
}
}
@@ -70,64 +70,64 @@ class Auction(seller: Actor, minBid: int, closing: Date) extends Actor {
object auction {
- val random = new java.util.Random();
+ val random = new java.util.Random()
- val minBid = 100;
- val closing = new Date(new Date().getTime() + 60000);
+ val minBid = 100
+ val closing = new Date(new Date().getTime() + 60000)
val seller = new Actor {
override def run() = {}
}
- val auction = new Auction(seller, minBid, closing);
+ val auction = new Auction(seller, minBid, closing)
def client(i: int, increment: int, top: int) = new Actor {
- val name = "Client " + i;
- def log(msg: String) = Console.println(name + ": " + msg);
- var running = true;
- var max: int = _;
- var current: int = 0;
+ val name = "Client " + i
+ def log(msg: String) = Console.println(name + ": " + msg)
+ var running = true
+ var max: int = _
+ var current: int = 0
override def run() = {
- log("started");
- auction send Inquire(this);
+ log("started")
+ auction send Inquire(this)
receive {
- case Status(maxBid, _) => {
- log("status(" + maxBid + ")");
- max = maxBid
- }
+ case Status(maxBid, _) => {
+ log("status(" + maxBid + ")")
+ max = maxBid
+ }
}
while (running) {
- if (max >= top)
- log("too high for me")
- else if (current < max) {
- current = max + increment;
- Thread.sleep(1 + random.nextInt(1000));
- auction send Offer(current, this);
- }
- receive {
- case BestOffer() => {
- log("bestOffer(" + current + ")");
- }
- case BeatenOffer(maxBid) => {
- log("beatenOffer(" + maxBid + ")");
- max = maxBid;
- }
- case AuctionConcluded(seller, maxBidder) => {
- log("auctionConcluded");
- }
- case AuctionOver() => {
- running = false;
- log("auctionOver");
- }
- }
+ if (max >= top)
+ log("too high for me")
+ else if (current < max) {
+ current = max + increment
+ Thread.sleep(1 + random.nextInt(1000))
+ auction send Offer(current, this)
+ }
+ receive {
+ case BestOffer() => {
+ log("bestOffer(" + current + ")")
+ }
+ case BeatenOffer(maxBid) => {
+ log("beatenOffer(" + maxBid + ")")
+ max = maxBid
+ }
+ case AuctionConcluded(seller, maxBidder) => {
+ log("auctionConcluded")
+ }
+ case AuctionOver() => {
+ running = false;
+ log("auctionOver")
+ }
+ }
}
}
}
def main(args: Array[String]) = {
- seller.start();
- auction.start();
- client(1, 20, 200).start();
- client(2, 10, 300).start();
+ seller.start()
+ auction.start()
+ client(1, 20, 200).start()
+ client(2, 10, 300).start()
}
}
diff --git a/docs/examples/boundedbuffer.scala b/docs/examples/boundedbuffer.scala
index 983a3a7bf5..89ad811c65 100644
--- a/docs/examples/boundedbuffer.scala
+++ b/docs/examples/boundedbuffer.scala
@@ -1,32 +1,32 @@
-package examples;
+package examples
object boundedbuffer {
- import concurrent.ops._;
+ import concurrent.ops._
class BoundedBuffer[a](N: Int) {
- var in, out, n = 0;
- val elems = new Array[a](N);
+ var in, out, n = 0
+ val elems = new Array[a](N)
def await(cond: => Boolean) = while (!cond) { wait() }
def put(x: a) = synchronized {
- await (n < N);
- elems(in) = x; in = (in + 1) % N; n = n + 1;
- if (n == 1) notifyAll();
+ await (n < N)
+ elems(in) = x; in = (in + 1) % N; n = n + 1
+ if (n == 1) notifyAll()
}
def get: a = synchronized {
- await (n != 0);
- val x = elems(out); out = (out + 1) % N ; n = n - 1;
- if (n == N - 1) notifyAll();
+ await (n != 0)
+ val x = elems(out); out = (out + 1) % N ; n = n - 1
+ if (n == N - 1) notifyAll()
x
}
}
def main(args: Array[String]) = {
- val buf = new BoundedBuffer[String](10);
- var cnt = 0;
+ val buf = new BoundedBuffer[String](10)
+ var cnt = 0
def produceString = { cnt = cnt + 1; cnt.toString() }
def consumeString(ss: String) = System.out.println(ss);
spawn { while (true) { val ssss = produceString; buf.put(ssss) } }
diff --git a/docs/examples/computeserver.scala b/docs/examples/computeserver.scala
index acc4a0b93e..7e63455258 100644
--- a/docs/examples/computeserver.scala
+++ b/docs/examples/computeserver.scala
@@ -5,28 +5,28 @@ import concurrent._, concurrent.ops._;
class ComputeServer(n: Int) {
private trait Job {
- type t;
- def task: t;
- def ret(x: t): Unit;
+ type t
+ def task: t
+ def ret(x: t): Unit
}
- private val openJobs = new Channel[Job]();
+ private val openJobs = new Channel[Job]()
private def processor(i: Int): Unit = {
while (true) {
- val job = openJobs.read;
- Console.println("read a job");
+ val job = openJobs.read
+ Console.println("read a job")
job.ret(job.task)
}
}
def future[a](p: => a): () => a = {
- val reply = new SyncVar[a]();
+ val reply = new SyncVar[a]()
openJobs.write{
new Job {
- type t = a;
- def task = p;
- def ret(x: a) = reply.set(x);
+ type t = a
+ def task = p
+ def ret(x: a) = reply.set(x)
}
}
() => reply.get
@@ -35,8 +35,8 @@ class ComputeServer(n: Int) {
spawn(replicate(0, n) { processor })
}
-object computeserver with Application {
- val server = new ComputeServer(1);
- val f = server.future(42);
+object computeserver extends Application {
+ val server = new ComputeServer(1)
+ val f = server.future(42)
Console.println(f())
}
diff --git a/docs/examples/futures.scala b/docs/examples/futures.scala
index 905d360612..79682b5b76 100644
--- a/docs/examples/futures.scala
+++ b/docs/examples/futures.scala
@@ -1,17 +1,17 @@
-package examples;
+package examples
-import concurrent.ops._;
+import concurrent.ops._
object futures {
- def someLengthyComputation = 1;
- def anotherLengthyComputation = 2;
- def f(x: Int) = x + x;
- def g(x: Int) = x * x;
+ def someLengthyComputation = 1
+ def anotherLengthyComputation = 2
+ def f(x: Int) = x + x
+ def g(x: Int) = x * x
def main(args: Array[String]): Unit = {
- val x = future(someLengthyComputation);
- anotherLengthyComputation;
- val y = f(x()) + g(x());
+ val x = future(someLengthyComputation)
+ anotherLengthyComputation
+ val y = f(x()) + g(x())
Console.println(y)
}
} \ No newline at end of file
diff --git a/docs/examples/iterators.scala b/docs/examples/iterators.scala
index 5f951156cf..c0bfb91cef 100644
--- a/docs/examples/iterators.scala
+++ b/docs/examples/iterators.scala
@@ -3,14 +3,14 @@ package examples;
object iterators {
def Array(elems: Double*): Array[Double] = {
- val ar = new Array[Double](elems.length);
+ val ar = new Array[Double](elems.length)
for (val i <- Iterator.range(0, elems.length))
- ar(i) = elems(i);
+ ar(i) = elems(i)
ar
}
def printArray(xs: Array[Double]) =
- Iterator.fromArray(xs) foreach { x => Console.println(x) };
+ Iterator.fromArray(xs) foreach { x => Console.println(x) }
def findGreater(xs: Array[Double], limit: Double) =
Iterator.fromArray(xs)
@@ -18,12 +18,11 @@ object iterators {
.filter{case Pair(x, i) => x > limit }
.map{case Pair(x, i) => i}
- def main(args: Array[String]) = {
- val ar = Array/*[Double]*/(6, 2, 8, 5, 1);
- printArray(ar);
- Console.println("Elements greater than 3.0:");
+ def main(args: Array[String]): Unit = {
+ val ar = Array/*[Double]*/(6, 2, 8, 5, 1)
+ printArray(ar)
+ Console.println("Elements greater than 3.0:")
findGreater(ar, 3.0) foreach { x => Console.println(ar(x)) }
}
}
-
diff --git a/docs/examples/maps.scala b/docs/examples/maps.scala
index 87489d496d..8b5158005b 100644
--- a/docs/examples/maps.scala
+++ b/docs/examples/maps.scala
@@ -1,28 +1,27 @@
-package examples;
+package examples
object maps {
- import scala.collection.immutable._;
+ import scala.collection.immutable._
trait MapStruct[kt, vt] {
- trait Map with Function1[kt, vt] {
- def extend(key: kt, value: vt): Map;
- def remove(key: kt): Map;
- def domain: Stream[kt];
- def range: Stream[vt];
+ trait Map extends Function1[kt, vt] {
+ def extend(key: kt, value: vt): Map
+ def remove(key: kt): Map
+ def domain: Stream[kt]
+ def range: Stream[vt]
}
- type map <: Map;
- val empty: map;
+ type map <: Map
+ val empty: map
}
class AlgBinTree[kt <: Ordered[kt], vt <: AnyRef]() extends MapStruct[kt, vt] {
- type map = AlgMap;
+ type map = AlgMap
- val empty: AlgMap = Empty();
+ val empty: AlgMap = Empty()
- private case class
- Empty(),
- Node(key: kt, value: vt, l: map, r: map) extends AlgMap {}
+ private case class Empty() extends AlgMap {}
+ private case class Node(key: kt, value: vt, l: map, r: map) extends AlgMap {}
trait AlgMap extends Map {
def apply(key: kt): vt = this match {
@@ -49,7 +48,7 @@ object maps {
else if (l == empty) r
else if (r == empty) l
else {
- val midKey = r.domain.head;
+ val midKey = r.domain.head
Node(midKey, r.apply(midKey), l, r.remove(midKey))
}
}
@@ -67,64 +66,64 @@ object maps {
}
class OOBinTree[kt <: Ordered[kt], vt <: AnyRef]() extends MapStruct[kt, vt] {
- type map = OOMap;
+ type map = OOMap
trait OOMap extends Map {
- def apply(key: kt): vt;
- def extend(key: kt, value: vt): map;
- def remove(key: kt): map;
- def domain: Stream[kt];
- def range: Stream[vt];
+ def apply(key: kt): vt
+ def extend(key: kt, value: vt): map
+ def remove(key: kt): map
+ def domain: Stream[kt]
+ def range: Stream[vt]
}
val empty: OOMap = new OOMap {
- def apply(key: kt): vt = null;
- def extend(key: kt, value: vt) = new Node(key, value, empty, empty);
- def remove(key: kt) = empty;
- def domain: Stream[kt] = Stream.empty;
- def range: Stream[vt] = Stream.empty;
+ def apply(key: kt): vt = null
+ def extend(key: kt, value: vt) = new Node(key, value, empty, empty)
+ def remove(key: kt) = empty
+ def domain: Stream[kt] = Stream.empty
+ def range: Stream[vt] = Stream.empty
}
private class Node(k: kt, v: vt, l: map, r: map) extends OOMap {
def apply(key: kt): vt =
- if (key < k) l.apply(key)
- else if (key > k) r.apply(key)
- else v;
+ if (key < k) l.apply(key)
+ else if (key > k) r.apply(key)
+ else v;
def extend(key: kt, value: vt): map =
- if (key < k) new Node(k, v, l.extend(key, value), r)
- else if (key > k) new Node(k, v, l, r.extend(key, value))
- else new Node(k, value, l, r);
+ if (key < k) new Node(k, v, l.extend(key, value), r)
+ else if (key > k) new Node(k, v, l, r.extend(key, value))
+ else new Node(k, value, l, r);
def remove(key: kt): map =
- if (key < k) new Node(k, v, l.remove(key), r)
- else if (key > k) new Node(k, v, l, r.remove(key))
- else if (l == empty) r
- else if (r == empty) l
- else {
- val midKey = r.domain.head;
- new Node(midKey, r(midKey), l, r.remove(midKey))
- }
+ if (key < k) new Node(k, v, l.remove(key), r)
+ else if (key > k) new Node(k, v, l, r.remove(key))
+ else if (l == empty) r
+ else if (r == empty) l
+ else {
+ val midKey = r.domain.head;
+ new Node(midKey, r(midKey), l, r.remove(midKey))
+ }
def domain: Stream[kt] = l.domain append Stream.cons(k, r.domain);
def range: Stream[vt] = l.range append Stream.cons(v, r.range);
}
}
class MutBinTree[kt <: Ordered[kt], vt <: AnyRef]() extends MapStruct[kt, vt] {
- type map = MutMap;
+ type map = MutMap
class MutMap(key: kt, value: vt) extends Map {
- val k = key;
- var v = value;
- var l, r = empty;
+ val k = key
+ var v = value
+ var l, r = empty
def apply(key: kt): vt =
if (this == empty) null
else if (key < k) l.apply(key)
else if (key > k) r.apply(key)
- else v;
+ else v
def extend(key: kt, value: vt): map =
if (this == empty) new MutMap(key, value)
else {
if (key < k) l = l.extend(key, value)
else if (key > k) r = r.extend(key, value)
- else v = value;
+ else v = value
this
}
@@ -135,7 +134,7 @@ object maps {
else if (l == empty) r
else if (r == empty) l
else {
- var mid = r;
+ var mid = r
while (!(mid.l == empty)) { mid = mid.l }
mid.r = r.remove(mid.k);
mid.l = l;
@@ -144,19 +143,19 @@ object maps {
def domain: Stream[kt] =
if (this == empty) Stream.empty;
- else l.domain append Stream.cons(k, r.domain);
+ else l.domain append Stream.cons(k, r.domain)
def range: Stream[vt] =
if (this == empty) Stream.empty;
- else l.range append Stream.cons(v, r.range);
+ else l.range append Stream.cons(v, r.range)
}
- val empty = new MutMap(null, null);
+ val empty = new MutMap(null, null)
}
- class Date(y: Int, m: Int, d: Int) with Ordered[Date] {
- def year = y;
- def month = m;
- def day = d;
+ class Date(y: Int, m: Int, d: Int) extends Ordered[Date] {
+ def year = y
+ def month = m
+ def day = d
def compareTo[b >: Date <% Ordered[b]](that: b): int = that match {
case other: Date =>
@@ -182,7 +181,7 @@ object maps {
}
def main(args: Array[String]) = {
- val t = new OOBinTree[Date, String]();
+ val t = new OOBinTree[Date, String]()
()
}
diff --git a/docs/examples/oneplacebuffer.scala b/docs/examples/oneplacebuffer.scala
index 7fa2ae8dba..2d6277913c 100644
--- a/docs/examples/oneplacebuffer.scala
+++ b/docs/examples/oneplacebuffer.scala
@@ -1,45 +1,46 @@
-package examples;
+package examples
object oneplacebuffer {
import scala.concurrent._;
class OnePlaceBuffer {
- private val m = new MailBox() {}; // An internal mailbox
- private case class Empty(), Full(x: Int); // Types of messages we deal with
+ private val m = new MailBox() {} // An internal mailbox
+ private case class Empty() // Types of messages we deal with
+ private case class Full(x: Int)
- m send Empty(); // Initialization
+ m send Empty() // Initialization
def write(x: Int): Unit = m receive {
case Empty() =>
- Console.println("put " + x);
+ Console.println("put " + x)
m send Full(x)
}
def read: Int = m receive {
case Full(x) =>
- Console.println("get " + x);
- m send Empty() ; x
+ Console.println("get " + x)
+ m send Empty(); x
}
}
def main(args: Array[String]) = {
- val buf = new OnePlaceBuffer;
- val random = new java.util.Random();
+ val buf = new OnePlaceBuffer
+ val random = new java.util.Random()
def producer(n: int): unit = {
- Thread.sleep(random.nextInt(1000));
- buf.write(n);
+ Thread.sleep(random.nextInt(1000))
+ buf.write(n)
producer(n + 1)
}
def consumer: unit = {
- Thread.sleep(random.nextInt(1000));
- val n = buf.read;
+ Thread.sleep(random.nextInt(1000))
+ val n = buf.read
consumer
}
- ops.spawn(producer(0));
+ ops.spawn(producer(0))
ops.spawn(consumer)
}
diff --git a/docs/examples/parsers1.scala b/docs/examples/parsers1.scala
index 143f354049..f2a5c48ac3 100644
--- a/docs/examples/parsers1.scala
+++ b/docs/examples/parsers1.scala
@@ -8,9 +8,9 @@ object parsers1 {
abstract class Parser {
- type Result = Option[inputType];
+ type Result = Option[inputType]
- def apply(in: inputType): Result;
+ def apply(in: inputType): Result
/*** p &&& q applies first p, and if that succeeds, then q
*/
@@ -39,79 +39,81 @@ object parsers1 {
def apply(in: inputType): Result = None
}
- def opt(p: Parser): Parser = p ||| empty; // p? = (p | <empty>)
- def rep(p: Parser): Parser = opt(rep1(p)); // p* = [p+]
- def rep1(p: Parser): Parser = p &&& rep(p); // p+ = p p*
+ def opt(p: Parser): Parser = p ||| empty // p? = (p | <empty>)
+ def rep(p: Parser): Parser = opt(rep1(p)) // p* = [p+]
+ def rep1(p: Parser): Parser = p &&& rep(p) // p+ = p p*
}
- abstract class ListParsers extends Parsers {
- def chr(p: char => boolean): Parser;
- def chr(c: char): Parser = chr(d: char => d == c);
+ mixin class ListParsers extends Parsers {
+ def chr(p: char => boolean): Parser
+ def chr(c: char): Parser = chr(d: char => d == c)
- def letter : Parser = chr(Character.isLetter);
- def digit : Parser = chr(Character.isDigit);
+ def letter : Parser = chr(c: char => Character.isLetter(c))
+ def digit : Parser = chr(c: char => Character.isDigit(c))
- def ident : Parser = letter &&& rep(letter ||| digit);
- def number : Parser = digit &&& rep(digit);
- def list : Parser = chr('(') &&& listElems &&& chr(')');
- def listElems : Parser = expr &&& (chr(',') &&& listElems ||| empty);
- def expr : Parser = ident ||| number ||| list;
+ def ident : Parser = letter &&& rep(letter ||| digit)
+ def number : Parser = digit &&& rep(digit)
+ def list : Parser = chr('(') &&& listElems &&& chr(')')
+ def listElems : Parser = expr &&& (chr(',') &&& listElems ||| empty)
+ def expr : Parser = ident ||| number ||| list
}
- abstract class ExprParsers extends Parsers {
- def chr(p: char => boolean): Parser;
- def chr(c: char): Parser = chr(d: char => d == c);
+ mixin class ExprParsers extends Parsers {
+ def chr(p: char => boolean): Parser
+ def chr(c: char): Parser = chr(d: char => d == c)
- def digit : Parser = chr(Character.isDigit);
- def number : Parser = digit &&& rep(digit);
- def summand : Parser = number ||| chr('(') &&& expr &&& chr(')');
+ def digit : Parser = chr(c: char => Character.isDigit(c))
+ def number : Parser = digit &&& rep(digit)
+ def summand : Parser = number ||| chr('(') &&& expr &&& chr(')')
def expr : Parser = summand &&& rep(chr('+') &&& summand)
}
class ParseString(s: String) extends Parsers {
- type inputType = int;
- val input = 0;
+ type inputType = Int
+ val input = 0
def chr(p: char => boolean) = new Parser {
def apply(in: int): Parser#Result =
- if (in < s.length() && p(s charAt in)) Some(in + 1);
- else None;
+ if (in < s.length() && p(s charAt in)) Some(in + 1)
+ else None
}
}
object TestList {
-
- def main(args: Array[String]): unit =
- if (args.length == 1) {
- val ps = new ListParsers with ParseString(args(0));
- ps.expr(ps.input) match {
- case Some(n) =>
- Console.println("parsed: " + args(0).substring(0, n));
- case None =>
- Console.println("nothing parsed");
+ def main(args: Array[String]): Unit =
+ Console.println(
+ if (args.length == 1) {
+ val ps = new ParseString(args(0)) with ListParsers
+ ps.expr(ps.input) match {
+ case Some(n) =>
+ "parsed: " + args(0).substring(0, n)
+ case None =>
+ "nothing parsed"
+ }
}
- }
- else
- Console.println("usage: java examples.TestList <expr-string>");
+ else
+ "usage: java examples.TestList <expr-string>"
+ )
}
object TestExpr {
-
def main(args: Array[String]): unit =
- if (args.length == 1) {
- val ps = new ExprParsers with ParseString(args(0));
- ps.expr(ps.input) match {
- case Some(n) =>
- Console.println("parsed: " + args(0).substring(0, n));
- case None =>
- Console.println("nothing parsed");
+ Console.println(
+ if (args.length == 1) {
+ val ps = new ParseString(args(0)) with ExprParsers
+ ps.expr(ps.input) match {
+ case Some(n) =>
+ "parsed: " + args(0).substring(0, n)
+ case None =>
+ "nothing parsed"
+ }
}
- }
- else
- Console.println("usage: java examples.TestExpr <expr-string>");
+ else
+ "usage: java examples.TestExpr <expr-string>"
+ )
}
def main(args: Array[String]): Unit = {
- TestList.main(Array("(a,b,(1,2))"));
+ TestList.main(Array("(a,b,(1,2))"))
TestExpr.main(Array("2+3+(4+1)"))
}
diff --git a/docs/examples/parsers2.scala b/docs/examples/parsers2.scala
index 47fa8d0f2e..a4211b3ebf 100644
--- a/docs/examples/parsers2.scala
+++ b/docs/examples/parsers2.scala
@@ -1,63 +1,68 @@
-package examples;
+package examples
object parsers2 {
- abstract class Tree{}
- case class Id (s: String) extends Tree {}
- case class Num(n: int) extends Tree {}
- case class Lst(elems: List[Tree]) extends Tree {}
+ abstract class Tree
+ case class Id (s: String) extends Tree
+ case class Num(n: int) extends Tree
+ case class Lst(elems: List[Tree]) extends Tree
- abstract class ListParsers extends CharParsers {
+ def isLetter = c: char => Character.isLetter(c)
+ def isLetterOrDigit: char => boolean = Character.isLetterOrDigit
+ def isDigit: char => boolean = Character.isDigit
+
+ mixin class ListParsers extends CharParsers {
def ident: Parser[Tree] =
for (
- val c: char <- chr(Character.isLetter);
- val cs: List[char] <- rep(chr(Character.isLetterOrDigit))
- ) yield Id((c :: cs).mkString("", "", ""));
+ val c: char <- chr(isLetter);
+ val cs: List[char] <- rep(chr(d: char => Character.isLetterOrDigit(d)))
+ ) yield Id((c :: cs).mkString("", "", ""))
def number: Parser[Tree] =
for (
- val d: char <- chr(Character.isDigit);
- val ds: List[char] <- rep(chr(Character.isDigit))
- ) yield Num(((d - '0') /: ds) ((x, digit) => x * 10 + digit - '0'));
+ val d: char <- chr(c: char => Character.isDigit(c));
+ val ds: List[char] <- rep(chr(c: char => Character.isDigit(c)))
+ ) yield Num(((d - '0') /: ds) ((x, digit) => x * 10 + digit - '0'))
def list: Parser[Tree] =
for (
val _ <- chr('(');
val es <- listElems ||| succeed(List());
val _ <- chr(')')
- ) yield Lst(es);
+ ) yield Lst(es)
def listElems: Parser[List[Tree]] =
for (
val x <- expr;
val xs <- chr(',') &&& listElems ||| succeed(List())
- ) yield x :: xs;
+ ) yield x :: xs
def expr: Parser[Tree] =
- list ||| ident ||| number;
+ list ||| ident ||| number
}
class ParseString(s: String) extends Parsers {
- type inputType = int;
- val input = 0;
+ type inputType = int
+ val input = 0
def any = new Parser[char] {
def apply(in: int): Parser[char]#Result =
- if (in < s.length()) Some(Pair(s charAt in, in + 1)) else None;
+ if (in < s.length()) Some(Pair(s charAt in, in + 1)) else None
}
}
def main(args: Array[String]): unit =
Console.println(
if (args.length == 1) {
- val ps = new ListParsers with ParseString(args(0));
+ val ps = new ParseString(args(0)) with ListParsers
ps.expr(ps.input) match {
- case Some(Pair(list, _)) => Console.println("parsed: " + list);
+ case Some(Pair(list, _)) => "parsed: " + list
case None => "nothing parsed"
}
- } else "usage: scala examples.parsers2 <expr-string>"
- );
+ }
+ else
+ "usage: scala examples.parsers2 <expr-string>"
+ )
}
-
diff --git a/docs/examples/pilib/elasticBuffer.scala b/docs/examples/pilib/elasticBuffer.scala
index 5e52a0fdce..e156cafbc2 100644
--- a/docs/examples/pilib/elasticBuffer.scala
+++ b/docs/examples/pilib/elasticBuffer.scala
@@ -1,76 +1,76 @@
-package examples.pilib;
+package examples.pilib
object elasticBuffer {
- import scala.concurrent.pilib._;
+ import scala.concurrent.pilib._
/**
- * Recursive type for channels that carry a "String" channel and
- * an object of the type we define.
- */
- class MetaChan extends Chan[Pair[Chan[String], MetaChan]];
+ * Recursive type for channels that carry a "String" channel and
+ * an object of the type we define.
+ */
+ class MetaChan extends Chan[Pair[Chan[String], MetaChan]]
- def Buffer(put: Chan[String], get: Chan[String]): unit = {
+ def Buffer(put: Chan[String], get: Chan[String]): Unit = {
/**
- * An empty buffer cell, ready to pass on (o,r) to the left.
- */
+ * An empty buffer cell, ready to pass on (o,r) to the left.
+ */
def Bl(i:Chan[String], l: MetaChan,
- o: Chan[String], r: MetaChan): unit =
- choice (
- l(Pair(o,r)) * (System.out.println("Removed one cell.")),
- i * (inp => Cl(i, l, o, r, inp))
- );
+ o: Chan[String], r: MetaChan): unit =
+ choice (
+ l(Pair(o,r)) * (System.out.println("Removed one cell.")),
+ i * (inp => Cl(i, l, o, r, inp))
+ )
/**
- * A buffer cell containing a value, ready to receive (o,r) from the right.
- */
+ * A buffer cell containing a value, ready to receive (o,r) from the right.
+ */
def Cl(i: Chan[String], l: MetaChan,
- o: Chan[String], r: MetaChan, content: String): unit =
- choice (
- o(content) * (Bl(i,l,o,r)),
- i * (inp => Dl(i,l,o,r,content, inp)),
- r * ( { case Pair(newo, newr) => Cl(i,l,newo,newr,content) })
- );
+ o: Chan[String], r: MetaChan, content: String): Unit =
+ choice (
+ o(content) * (Bl(i,l,o,r)),
+ i * (inp => Dl(i,l,o,r,content, inp)),
+ r * ( { case Pair(newo, newr) => Cl(i,l,newo,newr,content) })
+ )
/**
- * Two joined buffer cells, of type Cl.
- */
+ * Two joined buffer cells, of type Cl
+ */
def Dl(i: Chan[String], l: MetaChan,
- o: Chan[String], r: MetaChan,
- content: String, inp: String): unit = {
- val newlr = new MetaChan;
- val newio = new Chan[String];
- spawn < Cl(i, l, newio, newlr, inp) | Cl(newio, newlr, o, r,content) >;
+ o: Chan[String], r: MetaChan,
+ content: String, inp: String): Unit = {
+ val newlr = new MetaChan
+ val newio = new Chan[String]
+ spawn < Cl(i, l, newio, newlr, inp) | Cl(newio, newlr, o, r, content) >
}
// l and r channels for the leftmost and rightmost cell, respectively.
- val unused1 = new MetaChan;
- val unused2 = new MetaChan;
+ val unused1 = new MetaChan
+ val unused2 = new MetaChan
- Bl(put, unused1, get, unused2);
+ Bl(put, unused1, get, unused2)
}
- val random = new java.util.Random();
+ val random = new java.util.Random()
- def Producer(n: int, put: Chan[String]): unit = {
- Thread.sleep(1 + random.nextInt(1000));
- val msg = "object " + n;
- put.write(msg);
- System.out.println("Producer gave " + msg);
+ def Producer(n: int, put: Chan[String]): Unit = {
+ Thread.sleep(1 + random.nextInt(1000))
+ val msg = "object " + n
+ put.write(msg)
+ System.out.println("Producer gave " + msg)
Producer(n + 1, put)
}
- def Consumer(get: Chan[String]): unit = {
- Thread.sleep(1 + random.nextInt(1000));
- val msg = get.read;
- System.out.println("Consummer took " + msg);
+ def Consumer(get: Chan[String]): Unit = {
+ Thread.sleep(1 + random.nextInt(1000))
+ val msg = get.read
+ System.out.println("Consummer took " + msg)
Consumer(get)
}
- def main(args: Array[String]): unit = {
- val put = new Chan[String];
- val get = new Chan[String];
+ def main(args: Array[String]): Unit = {
+ val put = new Chan[String]
+ val get = new Chan[String]
spawn < Producer(0, put) | Consumer(get) | Buffer(put, get) >
}
diff --git a/docs/examples/pilib/handover.scala b/docs/examples/pilib/handover.scala
index 85fb899555..9725382c96 100644
--- a/docs/examples/pilib/handover.scala
+++ b/docs/examples/pilib/handover.scala
@@ -1,96 +1,95 @@
-package examples.pilib;
+package examples.pilib
/**
-* Handover example with recursive types for channels.
-*/
+ * Handover example with recursive types for channels.
+ */
object handoverRecursive {
- import concurrent.pilib._;
+ import concurrent.pilib._
- val random = new java.util.Random();
+ val random = new java.util.Random()
/**
- * Recursive type for channels that carry a channel "unit" and
- * an object of the type we define.
- */
- class Switch extends Chan[Pair[Chan[unit], Switch]];
+ * Recursive type for channels that carry a channel "unit" and
+ * an object of the type we define.
+ */
+ class Switch extends Chan[Pair[Chan[unit], Switch]]
/**
- * Car.
- */
+ * Car.
+ */
def Car(talk: Chan[unit], switch: Switch): unit =
choice (
switch * ({ case Pair(t,s) => Car(t, s) }),
talk(()) * ( {
- Thread.sleep(1 + random.nextInt(1000));
- System.out.println("Car emitted a message.");
- Car(talk, switch)
+ Thread.sleep(1 + random.nextInt(1000));
+ System.out.println("Car emitted a message.");
+ Car(talk, switch)
})
);
/**
- * Control center.
- */
+ * Control center.
+ */
def Control(talk1: Chan[unit], switch1: Switch,
- gain1: Switch, lose1: Switch,
- talk2: Chan[unit], switch2: Switch,
- gain2: Switch, lose2: Switch): unit
+ gain1: Switch, lose1: Switch,
+ talk2: Chan[unit], switch2: Switch,
+ gain2: Switch, lose2: Switch): unit
= {
def Control1: unit= {
Thread.sleep(1 + random.nextInt(1000));
lose1.write(Pair(talk2, switch2));
gain2.write(Pair(talk2, switch2));
- Control2;
+ Control2
}
def Control2: unit = {
Thread.sleep(1 + random.nextInt(1000));
lose2.write(Pair(talk1, switch1));
gain1.write(Pair(talk1, switch1));
- Control1;
+ Control1
}
- Control1;
+ Control1
}
/**
* Active transmitter.
*/
def ActiveTransmitter(id: String, talk: Chan[unit], switch: Switch,
- gain: Switch, lose: Switch): unit
+ gain: Switch, lose: Switch): unit
=
choice (
talk * (x => {
- System.out.println(id + " received a message.");
- ActiveTransmitter(id, talk, switch, gain, lose)
+ System.out.println(id + " received a message.")
+ ActiveTransmitter(id, talk, switch, gain, lose)
}),
lose * ({ case Pair(t, s) => {
- switch.write(Pair(t, s));
- IdleTransmitter(id, gain, lose)
+ switch.write(Pair(t, s))
+ IdleTransmitter(id, gain, lose)
}})
);
/**
- * Idle transmitter.
- */
+ * Idle transmitter.
+ */
def IdleTransmitter(id: String, gain: Switch, lose: Switch): unit = {
val Pair(t, s) = gain.read;
ActiveTransmitter(id, t, s, gain, lose)
}
def main(args: Array[String]): unit = {
- val talk1 = new Chan[unit];
- val switch1 = new Switch;
- val gain1 = new Switch;
- val lose1 = new Switch;
- val talk2 = new Chan[unit];
- val switch2 = new Switch;
- val gain2 = new Switch;
- val lose2 = new Switch;
+ val talk1 = new Chan[unit]
+ val switch1 = new Switch
+ val gain1 = new Switch
+ val lose1 = new Switch
+ val talk2 = new Chan[unit]
+ val switch2 = new Switch
+ val gain2 = new Switch
+ val lose2 = new Switch
spawn <
Car(talk1, switch1) |
ActiveTransmitter("Transmitter 1", talk1, switch1, gain1, lose1) |
IdleTransmitter("Transmitter 2", gain2, lose2) |
- Control(talk1, switch1, gain1, lose1, talk2, switch2, gain2, lose2)
- >
+ Control(talk1, switch1, gain1, lose1, talk2, switch2, gain2, lose2) >
}
}
@@ -110,12 +109,12 @@ object handoverCast {
choice (
switch * (o => {
val Pair(t,s) = o.asInstanceOf[Pair[Chan[Any],Chan[Any]]];
- Car(t, s)
+ Car(t, s)
}),
talk(()) * ( {
- Thread.sleep(1 + random.nextInt(1000));
- System.out.println("Car emitted a message.");
- Car(talk, switch)
+ Thread.sleep(1 + random.nextInt(1000));
+ System.out.println("Car emitted a message.");
+ Car(talk, switch)
})
);
@@ -123,11 +122,11 @@ object handoverCast {
* Control center.
*/
def Control(talk1: Chan[Any], switch1: Chan[Any],
- gain1: Chan[Any], lose1: Chan[Any],
- talk2: Chan[Any], switch2: Chan[Any],
- gain2: Chan[Any], lose2: Chan[Any]): unit
+ gain1: Chan[Any], lose1: Chan[Any],
+ talk2: Chan[Any], switch2: Chan[Any],
+ gain2: Chan[Any], lose2: Chan[Any]): unit
= {
- def Control1: unit= {
+ def Control1: unit = {
Thread.sleep(1 + random.nextInt(1000));
lose1.write(Pair(talk2, switch2));
gain2.write(Pair(talk2, switch2));
@@ -143,48 +142,45 @@ object handoverCast {
}
/**
- * Active transmitter.
- */
+ * Active transmitter.
+ */
def ActiveTransmitter(id: String, talk: Chan[Any], switch: Chan[Any],
- gain: Chan[Any], lose: Chan[Any]): unit
+ gain: Chan[Any], lose: Chan[Any]): unit
=
choice (
talk * (x => {
- System.out.println(id + " received a message.");
- ActiveTransmitter(id, talk, switch, gain, lose)
+ System.out.println(id + " received a message.")
+ ActiveTransmitter(id, talk, switch, gain, lose)
}),
lose * (o => {
- val Pair(t, s) = o.asInstanceOf[Pair[Chan[Any],Chan[Any]]];
- switch.write(Pair(t, s));
- IdleTransmitter(id, gain, lose)
+ val Pair(t, s) = o.asInstanceOf[Pair[Chan[Any],Chan[Any]]]
+ switch.write(Pair(t, s))
+ IdleTransmitter(id, gain, lose)
})
- );
+ )
/**
* Idle transmitter.
*/
def IdleTransmitter(id: String, gain: Chan[Any], lose: Chan[Any]): unit = {
- val Pair(t, s) = gain.read.asInstanceOf[Pair[Chan[Any],Chan[Any]]];
+ val Pair(t, s) = gain.read.asInstanceOf[Pair[Chan[Any],Chan[Any]]]
ActiveTransmitter(id, t, s, gain, lose)
}
def main(args: Array[String]): unit = {
- val talk1 = new Chan[Any];
- val switch1 = new Chan[Any];
- val gain1 = new Chan[Any];
- val lose1 = new Chan[Any];
- val talk2 = new Chan[Any];
- val switch2 = new Chan[Any];
- val gain2 = new Chan[Any];
- val lose2 = new Chan[Any];
+ val talk1 = new Chan[Any]
+ val switch1 = new Chan[Any]
+ val gain1 = new Chan[Any]
+ val lose1 = new Chan[Any]
+ val talk2 = new Chan[Any]
+ val switch2 = new Chan[Any]
+ val gain2 = new Chan[Any]
+ val lose2 = new Chan[Any]
spawn <
Car(talk1, switch1) |
ActiveTransmitter("Transmitter 1", talk1, switch1, gain1, lose1) |
IdleTransmitter("Transmitter 2", gain2, lose2) |
- Control(talk1, switch1, gain1, lose1, talk2, switch2, gain2, lose2)
- >
+ Control(talk1, switch1, gain1, lose1, talk2, switch2, gain2, lose2) >
}
}
-
-
diff --git a/docs/examples/pilib/mobilePhoneProtocol.scala b/docs/examples/pilib/mobilePhoneProtocol.scala
index 0b13f78fd3..385836318b 100644
--- a/docs/examples/pilib/mobilePhoneProtocol.scala
+++ b/docs/examples/pilib/mobilePhoneProtocol.scala
@@ -1,4 +1,4 @@
-package examples.pilib;
+package examples.pilib
/**
* Mobile phone protocol.
@@ -7,20 +7,20 @@ package examples.pilib;
*/
object mobilePhoneProtocol {
- import concurrent.pilib._;
+ import concurrent.pilib._
- val random = new java.util.Random();
+ val random = new java.util.Random()
// Internal messages exchanged by the protocol.
- trait Message;
+ trait Message
// Predefined messages used by the protocol.
- case class Data() extends Message;
- case class HoCmd() extends Message; // handover command
- case class HoAcc() extends Message; // handover access
- case class HoCom() extends Message; // handover complete
+ case class Data() extends Message;
+ case class HoCmd() extends Message; // handover command
+ case class HoAcc() extends Message; // handover access
+ case class HoCom() extends Message; // handover complete
case class HoFail() extends Message; // handover fail
- case class ChRel() extends Message; // release
+ case class ChRel() extends Message; // release
case class Voice(s: String) extends Message; // voice
case class Channel(n: Chan[Message]) extends Message; // channel
@@ -28,27 +28,27 @@ object mobilePhoneProtocol {
def CC(fa: Chan[Message], fp: Chan[Message], l: Chan[Channel]): unit =
choice (
- in * (v => { fa.write(Data()); fa.write(Voice(v)); CC(fa, fp, l) })
- ,
- l * (m_new => {
- fa.write(HoCmd());
- fa.write(m_new);
- choice (
- fp * ({ case HoCom() => {
- System.out.println("Mobile has moved from one cell to another");
- fa.write(ChRel());
- val Channel(m_old) = fa.read;
- l.write(Channel(m_old));
- CC(fp, fa, l)
- }})
- ,
- fa * ({ case HoFail() => {
- System.out.println("Mobile has failed to move from one cell to another");
- l.write(m_new);
- CC(fa, fp, l)
- }})
- )
- })
+ in * (v => { fa.write(Data()); fa.write(Voice(v)); CC(fa, fp, l) })
+ ,
+ l * (m_new => {
+ fa.write(HoCmd());
+ fa.write(m_new);
+ choice (
+ fp * ({ case HoCom() => {
+ System.out.println("Mobile has moved from one cell to another");
+ fa.write(ChRel());
+ val Channel(m_old) = fa.read;
+ l.write(Channel(m_old));
+ CC(fp, fa, l)
+ }})
+ ,
+ fa * ({ case HoFail() => {
+ System.out.println("Mobile has failed to move from one cell to another");
+ l.write(m_new);
+ CC(fa, fp, l)
+ }})
+ )
+ })
);
/*
@@ -74,58 +74,58 @@ object mobilePhoneProtocol {
*/
def BSa(f: Chan[Message], m: Chan[Message]): unit =
(f.read) match {
- case Data() => {
- val v = f.read;
- m.write(Data());
- m.write(v);
- BSa(f, m)
- }
- case HoCmd() => {
- val v = f.read;
- m.write(HoCmd());
- m.write(v);
- choice (
- f * ({ case ChRel() => {
- f.write(Channel(m));
- BSp(f, m)
- }})
- ,
- m * ({ case HoFail() => {
- f.write(HoFail());
- BSa(f, m)
- }})
- )
- }
+ case Data() => {
+ val v = f.read;
+ m.write(Data());
+ m.write(v);
+ BSa(f, m)
+ }
+ case HoCmd() => {
+ val v = f.read;
+ m.write(HoCmd());
+ m.write(v);
+ choice (
+ f * ({ case ChRel() => {
+ f.write(Channel(m));
+ BSp(f, m)
+ }})
+ ,
+ m * ({ case HoFail() => {
+ f.write(HoFail());
+ BSa(f, m)
+ }})
+ )
+ }
};
/**
- * Passive base station.
- */
+ * Passive base station.
+ */
def BSp(f: Chan[Message], m: Chan[Message]): unit = {
- val HoAcc = m.read;
- f.write(HoCom());
+ val HoAcc = m.read
+ f.write(HoCom())
BSa(f, m)
- };
+ }
/**
- * Mobile station.
- */
+ * Mobile station.
+ */
def MS(m: Chan[Message]): unit =
(m.read) match {
- case Data() => {
- val Voice(v) = m.read;
- out.write(v);
- MS(m)
- }
- case HoCmd() =>
- (m.read) match {
- case Channel(m_new) => {
- if (random.nextInt(1) == 0)
- choice ( m_new(HoAcc()) * (MS(m_new)) );
- else
- choice ( m(HoFail()) * (MS(m)) );
- }
- }
+ case Data() => {
+ val Voice(v) = m.read;
+ out.write(v);
+ MS(m)
+ }
+ case HoCmd() =>
+ (m.read) match {
+ case Channel(m_new) => {
+ if (random.nextInt(1) == 0)
+ choice ( m_new(HoAcc()) * (MS(m_new)) );
+ else
+ choice ( m(HoFail()) * (MS(m)) );
+ }
+ }
};
def P(fa: Chan[Message], fp: Chan[Message]): unit = {
diff --git a/docs/examples/pilib/piNat.scala b/docs/examples/pilib/piNat.scala
index 137c0e5e6a..8f0b11e27e 100644
--- a/docs/examples/pilib/piNat.scala
+++ b/docs/examples/pilib/piNat.scala
@@ -1,40 +1,40 @@
-package examples.pilib;
+package examples.pilib
-import scala.concurrent.pilib._;
+import scala.concurrent.pilib._
//import pilib._;
/** Church encoding of naturals in the Pi-calculus */
-object piNat with Application {
+object piNat extends Application {
/** Locations of Pi-calculus natural */
- class NatChan extends Chan[Triple[Chan[unit], Chan[NatChan], Chan[NatChan]]];
+ class NatChan extends Chan[Triple[Chan[unit], Chan[NatChan], Chan[NatChan]]]
/** Zero */
def Z(l: NatChan): unit = choice (
l * { case Triple(z, sd, d) => z.write(()) }
- );
+ )
/** Successor of Double */
def SD(n: NatChan, l: NatChan): unit = choice (
l * { case Triple(z, sd, d) => sd.write(n) }
- );
+ )
/** Double */
def D(n: NatChan, l: NatChan): unit = choice (
l * { case Triple(z, sd, d) => d.write(n) }
- );
+ )
/** Make "l" a location representing the natural "n" */
def make(n: int, l: NatChan): unit =
if (n == 0) Z(l)
else if (n % 2 == 0) { val l1 = new NatChan; spawn < D(l1, l) >; make(n/2, l1) }
- else { val l1 = new NatChan; spawn < SD(l1, l) >; make(n/2, l1) };
+ else { val l1 = new NatChan; spawn < SD(l1, l) >; make(n/2, l1) }
/** Consume the natural "m" and put it successor at location "n" */
def Succ(m: NatChan, n: NatChan): unit = {
- val z = new Chan[unit];
- val sd = new Chan[NatChan];
- val d = new Chan[NatChan];
+ val z = new Chan[unit]
+ val sd = new Chan[NatChan]
+ val d = new Chan[NatChan]
spawn < m.write(Triple(z, sd, d)) >;
choice (
z * { x => make(1, n) },
@@ -45,9 +45,9 @@ object piNat with Application {
/** Consume the natural "l" and put two copies at locations "m" and "n" */
def Copy(l: NatChan, m: NatChan, n: NatChan): unit = {
- val z = new Chan[unit];
- val sd = new Chan[NatChan];
- val d = new Chan[NatChan];
+ val z = new Chan[unit]
+ val sd = new Chan[NatChan]
+ val d = new Chan[NatChan]
spawn < l.write(Triple(z, sd, d)) >;
choice (
z * { x => spawn < Z(m) >; Z(n) },
@@ -62,9 +62,9 @@ object piNat with Application {
/** Consume the natural at location "n" and return its value */
def value(n: NatChan): int = {
- val z = new Chan[unit];
- val sd = new Chan[NatChan];
- val d = new Chan[NatChan];
+ val z = new Chan[unit]
+ val sd = new Chan[NatChan]
+ val d = new Chan[NatChan]
spawn < n.write(Triple(z, sd, d)) >;
choice (
z * { x => 0 },
@@ -74,19 +74,17 @@ object piNat with Application {
}
// Test
- val i = 42;
- val l = new NatChan;
- val l1 = new NatChan;
- val l2 = new NatChan;
- val l3 = new NatChan;
+ val i = 42
+ val l = new NatChan
+ val l1 = new NatChan
+ val l2 = new NatChan
+ val l3 = new NatChan
spawn <
make(i, l) |
Copy(l, l1, l2) |
Succ(l2, l3) |
System.out.println("" + i + " = " + value(l1)) |
- System.out.println("succ " + i + " = " + value(l3))
- >;
+ System.out.println("succ " + i + " = " + value(l3)) >
}
-
diff --git a/docs/examples/pilib/rwlock.scala b/docs/examples/pilib/rwlock.scala
index 0ed0f71a47..931f622f5a 100644
--- a/docs/examples/pilib/rwlock.scala
+++ b/docs/examples/pilib/rwlock.scala
@@ -1,4 +1,4 @@
-package examples.pilib;
+package examples.pilib
/**
* From Pi to Scala: Semaphores, monitors, read/write locks.
@@ -6,17 +6,17 @@ package examples.pilib;
*/
object rwlock {
- import scala.concurrent.pilib._;
+ import scala.concurrent.pilib._
class Signal extends Chan[unit] {
- def send = write(());
- def receive = read;
+ def send = write(())
+ def receive = read
}
class CountLock {
- private val busy = new Signal;
- def get = busy.send;
- def release = busy.receive;
+ private val busy = new Signal
+ def get = busy.send
+ def release = busy.receive
spawn < release >
}
@@ -30,43 +30,41 @@ object rwlock {
spawn < (while (true) {
choice (
busy * (x => free.receive),
- free * (x => ())
+ free * (x => ())
)
- })
- >
+ }) >
}
/** A monitor a la Java
*/
class JavaMonitor {
- private val lock = new Lock;
+ private val lock = new Lock
- private var waiting: List[Signal] = Nil;
+ private var waiting: List[Signal] = Nil
def Wait = {
- val s = new Signal;
- waiting = s :: waiting;
- lock.release;
- s.receive;
- lock.get;
+ val s = new Signal
+ waiting = s :: waiting
+ lock.release
+ s.receive
+ lock.get
}
- def Notify = {
+ def Notify =
if (!waiting.isEmpty) {
- waiting.head.send;
- waiting = waiting.tail;
+ waiting.head.send
+ waiting = waiting.tail
}
- }
- def NotifyAll = {
+ def NotifyAll =
while (!waiting.isEmpty) {
- waiting.head.send;
- waiting = waiting.tail;
+ waiting.head.send
+ waiting = waiting.tail
}
- }
- def await(cond: => boolean): unit = while (false == cond) (Wait)
+ def await(cond: => boolean): unit =
+ while (false == cond) (Wait)
}
/*
@@ -89,10 +87,10 @@ object rwlock {
/** A readers/writers lock. */
trait ReadWriteLock {
- def startRead: unit;
- def startWrite: unit;
- def endRead: unit;
- def endWrite: unit;
+ def startRead: unit
+ def startWrite: unit
+ def endRead: unit
+ def endWrite: unit
}
/**
@@ -100,58 +98,58 @@ object rwlock {
*/
class ReadWriteLock1 extends JavaMonitor with ReadWriteLock {
- private var nactive: int = 0;
- private var nwriters: int = 0;
+ private var nactive: int = 0
+ private var nwriters: int = 0
def status =
System.out.println(nactive + " active, " + nwriters + " writers");
def startRead = synchronized {
- await(nwriters == 0);
- nactive = nactive + 1;
+ await(nwriters == 0)
+ nactive = nactive + 1
status
}
def startWrite = synchronized {
- nwriters = nwriters + 1;
- await(nactive == 0);
- nactive = 1;
+ nwriters = nwriters + 1
+ await(nactive == 0)
+ nactive = 1
status
}
def endRead = synchronized {
- nactive = nactive - 1;
- if (nactive == 0) NotifyAll;
+ nactive = nactive - 1
+ if (nactive == 0) NotifyAll
status
}
def endWrite = synchronized {
- nwriters = nwriters - 1;
- nactive = 0;
- NotifyAll;
+ nwriters = nwriters - 1
+ nactive = 0
+ NotifyAll
status
}
}
/** A readers/writers lock, using semaphores
- */
+ */
class ReadWriteLock2 extends ReadWriteLock {
- private var rc: int = 0; // reading readers
- private var wc: int = 0; // writing writers
- private var rwc: int = 0; // waiting readers
- private var wwc: int = 0; // waiting writers
- private val mutex = new Lock;
- private val rsem = new Lock;
- private val wsem = new Lock;
+ private var rc: int = 0 // reading readers
+ private var wc: int = 0 // writing writers
+ private var rwc: int = 0 // waiting readers
+ private var wwc: int = 0 // waiting writers
+ private val mutex = new Lock
+ private val rsem = new Lock
+ private val wsem = new Lock
def startRead = {
mutex.get;
if (wwc > 0 || wc > 0) {
- rwc = rwc + 1;
- mutex.release;
- rsem.get;
- rwc = rwc - 1;
+ rwc = rwc + 1;
+ mutex.release;
+ rsem.get;
+ rwc = rwc - 1
}
rc = rc + 1;
if (rwc > 0) rsem.release;
@@ -161,13 +159,13 @@ object rwlock {
def startWrite = {
mutex.get;
if (rc > 0 || wc > 0) {
- wwc = wwc + 1;
- mutex.release;
- wsem.get;
- wwc = wwc - 1;
+ wwc = wwc + 1;
+ mutex.release;
+ wsem.get;
+ wwc = wwc - 1
}
wc = wc + 1;
- mutex.release;
+ mutex.release
}
def endRead = {
@@ -181,7 +179,7 @@ object rwlock {
mutex.get;
wc = wc - 1;
if (rwc > 0)
- rsem.release
+ rsem.release
else if (wwc > 0) wsem.release;
mutex.release
}
@@ -191,48 +189,48 @@ object rwlock {
*/
class ReadWriteLock3 extends ReadWriteLock {
- private val sr = new Signal;
- private val er = new Signal;
- private val sw = new Signal;
- private val ew = new Signal;
+ private val sr = new Signal
+ private val er = new Signal
+ private val sw = new Signal
+ private val ew = new Signal
- def startRead = sr.send;
- def startWrite = sw.send;
- def endRead = er.send;
- def endWrite = ew.send;
+ def startRead = sr.send
+ def startWrite = sw.send
+ def endRead = er.send
+ def endWrite = ew.send
private def rwlock: unit = choice (
sr * (x => reading(1)),
sw * (x => { ew.receive; rwlock })
- );
+ )
private def reading(n: int): unit = choice (
sr * (x => reading(n+1)),
er * (x => if (n == 1) rwlock else reading(n-1))
- );
+ )
- spawn < rwlock >;
+ spawn < rwlock >
}
/** Same, with sequencing
*/
class ReadWriteLock4 extends ReadWriteLock {
- private val rwlock = new ReadWriteLock3;
+ private val rwlock = new ReadWriteLock3
- private val sr = new Signal;
- private val ww = new Signal;
- private val sw = new Signal;
+ private val sr = new Signal
+ private val ww = new Signal
+ private val sw = new Signal
- def startRead = sr.send;
- def startWrite = { ww.send; sw.send; }
- def endRead = rwlock.endRead;
- def endWrite = rwlock.endWrite;
+ def startRead = sr.send
+ def startWrite = { ww.send; sw.send }
+ def endRead = rwlock.endRead
+ def endWrite = rwlock.endWrite
private def queue: unit = choice (
sr * (x => { rwlock.startRead ; queue }),
ww * (x => { rwlock.startWrite; sw.receive; queue })
- );
+ )
spawn < queue >;
}
@@ -241,16 +239,16 @@ object rwlock {
*/
class ReadWriteLock5 extends ReadWriteLock {
- private val sr = new Signal;
- private val er = new Signal;
- private val ww = new Signal;
- private val sw = new Signal;
- private val ew = new Signal;
+ private val sr = new Signal
+ private val er = new Signal
+ private val ww = new Signal
+ private val sw = new Signal
+ private val ew = new Signal
- def startRead = sr.send;
- def startWrite = { ww.send; sw.send; }
- def endRead = er.send;
- def endWrite = ew.send;
+ def startRead = sr.send
+ def startWrite = { ww.send; sw.send }
+ def endRead = er.send
+ def endWrite = ew.send
private def Reading(nr: int, nw: int): unit =
if (nr == 0 && nw == 0)
@@ -260,12 +258,12 @@ object rwlock {
)
else if (nr == 0 && nw != 0) {
sw.receive;
- Writing(nw);
+ Writing(nw);
}
else if (nr != 0 && nw == 0)
choice (
sr * (x => Reading(nr + 1, 0)),
- er * (x => Reading(nr - 1, 0)),
+ er * (x => Reading(nr - 1, 0)),
ww * (x => Reading(nr, 1))
)
else if (nr != 0 && nw != 0)
@@ -284,36 +282,36 @@ object rwlock {
}
/**
- * Main function.
- */
+ * Main function.
+ */
def main(args: Array[String]): unit = {
- val random = new java.util.Random();
+ val random = new java.util.Random()
def reader(i: int, rwlock: ReadWriteLock): unit = {
- Thread.sleep(1 + random.nextInt(100));
- System.err.println("Reader " + i + " wants to read.");
- rwlock.startRead;
- System.err.println("Reader " + i + " is reading.");
- Thread.sleep(1 + random.nextInt(100));
- rwlock.endRead;
- System.err.println("Reader " + i + " has read.");
+ Thread.sleep(1 + random.nextInt(100))
+ System.err.println("Reader " + i + " wants to read.")
+ rwlock.startRead
+ System.err.println("Reader " + i + " is reading.")
+ Thread.sleep(1 + random.nextInt(100))
+ rwlock.endRead
+ System.err.println("Reader " + i + " has read.")
reader(i, rwlock)
}
def writer(i: int, rwlock: ReadWriteLock): unit = {
- Thread.sleep(1 + random.nextInt(100));
- System.err.println("Writer " + i + " wants to write.");
- rwlock.startWrite;
- System.err.println("Writer " + i + " is writing.");
- Thread.sleep(1 + random.nextInt(100));
- rwlock.endWrite;
- System.err.println("Writer " + i + " has written.");
+ Thread.sleep(1 + random.nextInt(100))
+ System.err.println("Writer " + i + " wants to write.")
+ rwlock.startWrite
+ System.err.println("Writer " + i + " is writing.")
+ Thread.sleep(1 + random.nextInt(100))
+ rwlock.endWrite
+ System.err.println("Writer " + i + " has written.")
writer(i, rwlock)
}
val n = try { Integer.parseInt(args(0)) } catch { case _ => 0 }
if (n < 1 || 5 < n) {
- Console.println("Usage: scala examples.pilib.rwlock <n> (n=1..5)");
+ Console.println("Usage: scala examples.pilib.rwlock <n> (n=1..5)")
exit
}
val rwlock = n match {
@@ -323,8 +321,8 @@ object rwlock {
case 4 => new ReadWriteLock4
case 5 => new ReadWriteLock5
}
- List.range(0, 5) foreach (i => spawn < reader(i, rwlock) >);
- List.range(0, 5) foreach (i => spawn < writer(i, rwlock) >);
+ List.range(0, 5) foreach (i => spawn < reader(i, rwlock) >)
+ List.range(0, 5) foreach (i => spawn < writer(i, rwlock) >)
}
}
diff --git a/docs/examples/pilib/scheduler.scala b/docs/examples/pilib/scheduler.scala
index 3b08a9df66..8946a5a0b2 100644
--- a/docs/examples/pilib/scheduler.scala
+++ b/docs/examples/pilib/scheduler.scala
@@ -1,19 +1,19 @@
-package examples.pilib;
+package examples.pilib
-import scala.concurrent.pilib._;
+import scala.concurrent.pilib._
object scheduler {
/**
- * Random number generator.
- */
- val random = new java.util.Random();
+ * Random number generator.
+ */
+ val random = new java.util.Random()
//***************** Scheduler ******************//
/**
- * A cell of the scheduler whose attached agent is allowed to start.
- */
+ * A cell of the scheduler whose attached agent is allowed to start.
+ */
def A(a: Chan[unit], b: Chan[unit])(d: Chan[unit], c: Chan[unit]): unit = {
///- ... complete here ...
choice ( a * { x => C(a, b)(d, c) })
@@ -21,8 +21,8 @@ object scheduler {
}
/**
- * A cell of the scheduler in another intermediate state.
- */
+ * A cell of the scheduler in another intermediate state.
+ */
def C(a: Chan[unit], b: Chan[unit])(d: Chan[unit], c: Chan[unit]): unit = {
///- ... complete here ...
choice (c * { x => B(a, b)(d, c) })
@@ -30,8 +30,8 @@ object scheduler {
}
/**
- * A cell of the scheduler whose attached agent is allowed to finish.
- */
+ * A cell of the scheduler whose attached agent is allowed to finish.
+ */
def B(a: Chan[unit], b: Chan[unit])(d: Chan[unit], c: Chan[unit]): unit = {
///- ... complete here ...
// choice (b * { x => D(a, b)(d, c) }) // incorrect naive solution
@@ -43,8 +43,8 @@ object scheduler {
}
/**
- * A cell of the scheduler whose attached agent is not yet allowed to start.
- */
+ * A cell of the scheduler whose attached agent is not yet allowed to start.
+ */
def D(a: Chan[unit], b: Chan[unit])(d: Chan[unit], c: Chan[unit]): unit = {
///- ... complete here ...
choice (d(()) * A(a, b)(d, c))
@@ -56,44 +56,44 @@ object scheduler {
def agent(i: Int)(a: Chan[unit], b: Chan[unit]): unit = {
// 50% chance that we sleep forever
if (i == 0 && random.nextInt(10) < 5) {
- a.attach(x => System.out.println("Start and sleeps ----> " + i));
- Thread.sleep(random.nextInt(1000));
- a.write(());
+ a.attach(x => System.out.println("Start and sleeps ----> " + i))
+ Thread.sleep(random.nextInt(1000))
+ a.write(())
}
else {
- a.attach(x => System.out.println("Start ----> " + i));
- b.attach(x => System.out.println("Stop -> " + i));
- Thread.sleep(random.nextInt(1000));
- a.write(());
- Thread.sleep(random.nextInt(1000));
- b.write(());
- agent(i)(a, b)
+ a.attach(x => System.out.println("Start ----> " + i))
+ b.attach(x => System.out.println("Stop -> " + i))
+ Thread.sleep(random.nextInt(1000))
+ a.write(())
+ Thread.sleep(random.nextInt(1000))
+ b.write(())
+ agent(i)(a, b)
}
}
//***************** Entry function ******************//
/**
- * Creates a scheduler for five agents (programs).
- */
+ * Creates a scheduler for five agents (programs).
+ */
def main(args: Array[String]): unit = {
- val agentNb = 5;
- val agents = List.range(0, agentNb) map agent;
- scheduleAgents(agents);
+ val agentNb = 5
+ val agents = List.range(0, agentNb) map agent
+ scheduleAgents(agents)
}
//***************** Infrastructure *****************//
/**
- * A cell is modelled as a function that takes as parameters
- * input and output channels and which returns nothing.
- */
- type Cell = (Chan[unit], Chan[unit]) => unit;
+ * A cell is modelled as a function that takes as parameters
+ * input and output channels and which returns nothing.
+ */
+ type Cell = (Chan[unit], Chan[unit]) => unit
/**
- * Creates a cell composed of two cells linked together.
- */
+ * Creates a cell composed of two cells linked together.
+ */
def join(cell1: Cell, cell2: Cell): Cell =
(l: Chan[unit], r: Chan[unit]) => {
val link = new Chan[unit];
@@ -101,49 +101,50 @@ object scheduler {
};
/**
- * Links the output of a cell to its input.
- */
+ * Links the output of a cell to its input.
+ */
def close(cell: Cell): unit = {
- val a = new Chan[unit];
+ val a = new Chan[unit]
cell(a, a)
}
/**
- * Creates a cell consisting of a chain of cells.
- */
+ * Creates a cell consisting of a chain of cells.
+ */
def chain(cells: List[Cell]): Cell =
- cells reduceLeft join;
+ cells reduceLeft join
/**
- * Creates a cell consisting of a chain of cells.
- */
+ * Creates a cell consisting of a chain of cells.
+ */
def makeRing(cells: List[Cell]): unit =
- close(chain(cells));
+ close(chain(cells))
/**
- * An agent is modelled as a function that takes as parameters channels to
- * signal that it has started or finished.
- */
- type Agent = (Chan[unit], Chan[unit]) => unit;
+ * An agent is modelled as a function that takes as parameters channels to
+ * signal that it has started or finished.
+ */
+ type Agent = (Chan[unit], Chan[unit]) => unit
/**
- * Takes a list of agents and schedules them.
- */
+ * Takes a list of agents and schedules them.
+ */
def scheduleAgents(agents: List[Agent]): unit = {
var firstAgent = true;
val cells = agents map (ag => {
val a = new Chan[unit];
val b = new Chan[unit];
spawn < ag(a, b) >;
- if (firstAgent) {
- firstAgent = false;
- A(a, b)
+ (d: Chan[unit], c: Chan[unit]) => if (firstAgent) {
+ firstAgent = false;
+ A(a, b)(d, c)
}
else
- D(a, b)
+ D(a, b)(d, c)
});
makeRing(cells)
}
+
}
diff --git a/docs/examples/pilib/semaphore.scala b/docs/examples/pilib/semaphore.scala
index cfb0c8e5a2..30e3c00975 100644
--- a/docs/examples/pilib/semaphore.scala
+++ b/docs/examples/pilib/semaphore.scala
@@ -1,70 +1,70 @@
-package examples.pilib;
+package examples.pilib
/** Solution of exercise session 6 (first question). */
object semaphore {
- import scala.concurrent.pilib._;
+ import scala.concurrent.pilib._
class Signal extends Chan[unit] {
- def send = write(());
- def receive = read;
+ def send = write(())
+ def receive = read
}
/** Interface. */
trait Semaphore {
- def get: unit;
- def release: unit;
+ def get: unit
+ def release: unit
}
/** First implementation. */
class Sem1 extends Semaphore {
- private val g = new Signal;
- private val r = new Signal;
+ private val g = new Signal
+ private val r = new Signal
- def get: unit = g.send;
- def release: unit = r.send;
+ def get: unit = g.send
+ def release: unit = r.send
private def Sched: unit = choice (
g * (x => { r.receive; Sched }),
r * (x => Sched)
- );
- spawn< Sched >;
+ )
+ spawn< Sched >
}
/** Second implementation. */
class Sem2 extends Semaphore {
- private val a = new Signal;
- private val na = new Signal;
+ private val a = new Signal
+ private val na = new Signal
def get: unit = { a.receive; spawn< na.send > }
def release: unit = choice (
a * (x => spawn< a.send >),
na * (x => spawn< a.send >)
- );
- spawn< a.send >;
+ )
+ spawn< a.send >
}
/** Test program. */
def main(args: Array[String]): unit = {
- val random = new java.util.Random();
- val sem = new Sem2;
+ val random = new java.util.Random()
+ val sem = new Sem2
def mutex(p: => unit): unit = { sem.get; p; sem.release }
spawn< {
Thread.sleep(1 + random.nextInt(100));
mutex( {
- System.out.println("a1");
- Thread.sleep(1 + random.nextInt(100));
- System.out.println("a2")
+ System.out.println("a1");
+ Thread.sleep(1 + random.nextInt(100));
+ System.out.println("a2")
} )
} | {
Thread.sleep(1 + random.nextInt(100));
mutex( {
- System.out.println("b1");
- Thread.sleep(1 + random.nextInt(100));
- System.out.println("b2")
+ System.out.println("b1");
+ Thread.sleep(1 + random.nextInt(100));
+ System.out.println("b2")
} )
} >;
}
diff --git a/docs/examples/pilib/twoPlaceBuffer.scala b/docs/examples/pilib/twoPlaceBuffer.scala
index 686547b344..020f3e4992 100644
--- a/docs/examples/pilib/twoPlaceBuffer.scala
+++ b/docs/examples/pilib/twoPlaceBuffer.scala
@@ -1,53 +1,53 @@
-package examples.pilib;
+package examples.pilib
-import scala.concurrent.pilib._;
+import scala.concurrent.pilib._
/** Two-place buffer specification and implementation. */
-object twoPlaceBuffer with Application {
+object twoPlaceBuffer extends Application {
/**
- * Specification.
- */
- def Spec[a](in: Chan[a], out: Chan[a]): unit = {
+ * Specification.
+ */
+ def Spec[a](in: Chan[a], out: Chan[a]): Unit = {
def B0: unit = choice (
in * (x => B1(x))
- );
+ )
def B1(x: a): unit = choice (
out(x) * (B0),
in * (y => B2(x, y))
- );
+ )
def B2(x: a, y: a): unit = choice (
out(x) * (B1(y))
- );
+ )
B0
}
/**
- * Implementation using two one-place buffers.
- */
+ * Implementation using two one-place buffers.
+ */
def Impl[a](in: Chan[a], out: Chan[a]): unit = {
///- ... complete here ...
// one-place buffer
- def OnePlaceBuffer[a](in: Chan[a], out: Chan[a]): unit = {
- def B0: unit = choice ( in * (x => B1(x)) );
- def B1(x: a): unit = choice ( out(x) * (B0));
+ def OnePlaceBuffer[a](in: Chan[a], out: Chan[a]): Unit = {
+ def B0: unit = choice ( in * (x => B1(x)) )
+ def B1(x: a): unit = choice ( out(x) * (B0))
B0
}
- val hidden = new Chan[a];
+ val hidden = new Chan[a]
spawn < OnePlaceBuffer(in, hidden) | OnePlaceBuffer(hidden, out) >
///+
}
- val random = new java.util.Random();
+ val random = new java.util.Random()
- def Producer(n: Int, in: Chan[String]): unit = {
- Thread.sleep(random.nextInt(1000));
- val msg = "" + n;
- choice (in(msg) * {});
+ def Producer(n: Int, in: Chan[String]): Unit = {
+ Thread.sleep(random.nextInt(1000))
+ val msg = "" + n
+ choice (in(msg) * {})
Producer(n + 1, in)
}
@@ -57,10 +57,10 @@ object twoPlaceBuffer with Application {
Consumer(out)
}
- val in = new Chan[String];
- in.attach(s => System.out.println("put " + s));
- val out = new Chan[String];
- out.attach(s => System.out.println("get " + s));
+ val in = new Chan[String]
+ in.attach(s => System.out.println("put " + s))
+ val out = new Chan[String]
+ out.attach(s => System.out.println("get " + s))
//spawn < Producer(0, in) | Consumer(out) | Spec(in, out) >
spawn < Producer(0, in) | Consumer(out) | Impl(in, out) >
diff --git a/docs/examples/sort.scala b/docs/examples/sort.scala
index 6554a2415b..cc06f19366 100644
--- a/docs/examples/sort.scala
+++ b/docs/examples/sort.scala
@@ -1,47 +1,47 @@
-package examples;
+package examples
object sort {
def sort(a: Array[Int]): Unit = {
def swap(i: Int, j: Int): Unit = {
- val t = a(i); a(i) = a(j); a(j) = t;
+ val t = a(i); a(i) = a(j); a(j) = t
}
def sort1(l: Int, r: Int): Unit = {
- val pivot = a((l + r) / 2);
- var i = l;
- var j = r;
+ val pivot = a((l + r) / 2)
+ var i = l
+ var j = r
while (i <= j) {
while (a(i) < pivot) { i = i + 1 }
while (a(j) > pivot) { j = j - 1 }
if (i <= j) {
- swap(i, j);
- i = i + 1;
- j = j - 1;
+ swap(i, j)
+ i = i + 1
+ j = j - 1
}
}
- if (l < j) sort1(l, j);
- if (j < r) sort1(i, r);
+ if (l < j) sort1(l, j)
+ if (j < r) sort1(i, r)
}
if (a.length > 0)
- sort1(0, a.length - 1);
+ sort1(0, a.length - 1)
}
def println(ar: Array[Int]) = {
def print1 = {
def iter(i: Int): String =
- ar(i) + (if (i < ar.length-1) "," + iter(i+1) else "");
+ ar(i) + (if (i < ar.length-1) "," + iter(i+1) else "")
if (ar.length == 0) "" else iter(0)
}
Console.println("[" + print1 + "]")
}
- def main(args: Array[String]) = {
- val ar = Array(6, 2, 8, 5, 1);
- println(ar);
- sort(ar);
+ def main(args: Array[String]): Unit = {
+ val ar = Array(6, 2, 8, 5, 1)
+ println(ar)
+ sort(ar)
println(ar)
}
diff --git a/docs/examples/sort1.scala b/docs/examples/sort1.scala
index 406bf7c911..98f1370e65 100644
--- a/docs/examples/sort1.scala
+++ b/docs/examples/sort1.scala
@@ -1,4 +1,4 @@
-package examples;
+package examples
object sort1 {
@@ -6,16 +6,16 @@ object sort1 {
if (a.length < 2)
a
else {
- val pivot = a(a.length / 2);
- sort(a.filter(x => x < pivot))
- ::: a.filter(x => x == pivot)
- ::: sort(a.filter(x => x > pivot))
+ val pivot = a(a.length / 2)
+ sort(a.filter(x => x < pivot)) :::
+ a.filter(x => x == pivot) :::
+ sort(a.filter(x => x > pivot))
}
}
def main(args: Array[String]) = {
- val xs = List(6, 2, 8, 5, 1);
- Console.println(xs);
+ val xs = List(6, 2, 8, 5, 1)
+ Console.println(xs)
Console.println(sort(xs))
}
diff --git a/docs/examples/sort2.scala b/docs/examples/sort2.scala
index 53b2f89174..1e471b89df 100644
--- a/docs/examples/sort2.scala
+++ b/docs/examples/sort2.scala
@@ -1,4 +1,4 @@
-package examples;
+package examples
object sort2 {
@@ -6,19 +6,19 @@ object sort2 {
if (a.length < 2)
a
else {
- val pivot = a(a.length / 2);
- def lePivot(x: Int) = x < pivot;
- def gtPivot(x: Int) = x > pivot;
- def eqPivot(x: Int) = x == pivot;
- sort(a filter lePivot)
- ::: sort(a filter eqPivot)
- ::: sort(a filter gtPivot)
+ val pivot = a(a.length / 2)
+ def lePivot(x: Int) = x < pivot
+ def gtPivot(x: Int) = x > pivot
+ def eqPivot(x: Int) = x == pivot
+ sort(a filter lePivot) :::
+ sort(a filter eqPivot) :::
+ sort(a filter gtPivot)
}
}
- def main(args: Array[String]) = {
- val xs = List(6, 2, 8, 5, 1);
- Console.println(xs);
+ def main(args: Array[String]): Unit = {
+ val xs = List(6, 2, 8, 5, 1)
+ Console.println(xs)
Console.println(sort(xs))
}
diff --git a/docs/examples/typeinf.scala b/docs/examples/typeinf.scala
index a9ac59968b..d9b2b5f3d1 100644
--- a/docs/examples/typeinf.scala
+++ b/docs/examples/typeinf.scala
@@ -1,4 +1,4 @@
-package examples;
+package examples
object typeinf {
@@ -14,7 +14,7 @@ case class App(f: Term, e: Term) extends Term {
override def toString() = "(" + f + " " + e + ")"
}
case class Let(x: String, e: Term, f: Term) extends Term {
- override def toString() = "let " + x + " = " + e + " in " + f;
+ override def toString() = "let " + x + " = " + e + " in " + f
}
sealed trait Type {}
@@ -31,18 +31,18 @@ case class Tycon(k: String, ts: List[Type]) extends Type {
object typeInfer {
- private var n: Int = 0;
+ private var n: Int = 0
def newTyvar(): Type = { n = n + 1 ; Tyvar("a" + n) }
- trait Subst with Function1[Type,Type] {
- def lookup(x: Tyvar): Type;
+ trait Subst extends Function1[Type, Type] {
+ def lookup(x: Tyvar): Type
def apply(t: Type): Type = t match {
- case tv @ Tyvar(a) => val u = lookup(tv); if (t == u) t else apply(u);
+ case tv @ Tyvar(a) => val u = lookup(tv); if (t == u) t else apply(u)
case Arrow(t1, t2) => Arrow(apply(t1), apply(t2))
case Tycon(k, ts) => Tycon(k, ts map apply)
}
def extend(x: Tyvar, t: Type) = new Subst {
- def lookup(y: Tyvar): Type = if (x == y) t else Subst.this.lookup(y);
+ def lookup(y: Tyvar): Type = if (x == y) t else Subst.this.lookup(y)
}
}
@@ -50,10 +50,10 @@ object typeInfer {
case class TypeScheme(tyvars: List[Tyvar], tpe: Type) {
def newInstance: Type =
- (emptySubst /: tyvars) ((s, tv) => s.extend(tv, newTyvar())) (tpe);
+ (emptySubst /: tyvars) ((s, tv) => s.extend(tv, newTyvar())) (tpe)
}
- type Env = List[Pair[String, TypeScheme]];
+ type Env = List[Pair[String, TypeScheme]]
def lookup(env: Env, x: String): TypeScheme = env match {
case List() => null
@@ -61,19 +61,19 @@ object typeInfer {
}
def gen(env: Env, t: Type): TypeScheme =
- TypeScheme(tyvars(t) diff tyvars(env), t);
+ TypeScheme(tyvars(t) diff tyvars(env), t)
def tyvars(t: Type): List[Tyvar] = t match {
case tv @ Tyvar(a) => List(tv)
case Arrow(t1, t2) => tyvars(t1) union tyvars(t2)
- case Tycon(k, ts) => (List[Tyvar]() /: ts) ((tvs, t) => tvs union tyvars(t));
+ case Tycon(k, ts) => (List[Tyvar]() /: ts) ((tvs, t) => tvs union tyvars(t))
}
def tyvars(ts: TypeScheme): List[Tyvar] =
tyvars(ts.tpe) diff ts.tyvars;
def tyvars(env: Env): List[Tyvar] =
- (List[Tyvar]() /: env) ((tvs, nt) => tvs union tyvars(nt._2));
+ (List[Tyvar]() /: env) ((tvs, nt) => tvs union tyvars(nt._2))
def mgu(t: Type, u: Type, s: Subst): Subst = Pair(s(t), s(u)) match {
case Pair(Tyvar(a), Tyvar(b)) if (a == b) =>
@@ -86,51 +86,52 @@ object typeInfer {
mgu(t1, u1, mgu(t2, u2, s))
case Pair(Tycon(k1, ts), Tycon(k2, us)) if (k1 == k2) =>
(s /: (ts zip us)) ((s, tu) => mgu(tu._1, tu._2, s))
- case _ => throw new TypeError("cannot unify " + s(t) + " with " + s(u))
+ case _ =>
+ throw new TypeError("cannot unify " + s(t) + " with " + s(u))
}
case class TypeError(s: String) extends Exception(s) {}
def tp(env: Env, e: Term, t: Type, s: Subst): Subst = {
- current = e;
+ current = e
e match {
case Var(x) =>
- val u = lookup(env, x);
- if (u == null) throw new TypeError("undefined: " + x);
- else mgu(u.newInstance, t, s)
+ val u = lookup(env, x)
+ if (u == null) throw new TypeError("undefined: " + x)
+ else mgu(u.newInstance, t, s)
case Lam(x, e1) =>
- val a, b = newTyvar();
- val s1 = mgu(t, Arrow(a, b), s);
- val env1 = Pair(x, TypeScheme(List(), a)) :: env;
- tp(env1, e1, b, s1)
+ val a, b = newTyvar()
+ val s1 = mgu(t, Arrow(a, b), s)
+ val env1 = Pair(x, TypeScheme(List(), a)) :: env
+ tp(env1, e1, b, s1)
case App(e1, e2) =>
- val a = newTyvar();
- val s1 = tp(env, e1, Arrow(a, t), s);
- tp(env, e2, a, s1)
+ val a = newTyvar()
+ val s1 = tp(env, e1, Arrow(a, t), s)
+ tp(env, e2, a, s1)
case Let(x, e1, e2) =>
- val a = newTyvar();
- val s1 = tp(env, e1, a, s);
- tp(Pair(x, gen(env, s1(a))) :: env, e2, t, s1)
+ val a = newTyvar()
+ val s1 = tp(env, e1, a, s)
+ tp(Pair(x, gen(env, s1(a))) :: env, e2, t, s1)
}
}
- var current: Term = null;
+ var current: Term = null
def typeOf(env: Env, e: Term): Type = {
- val a = newTyvar();
+ val a = newTyvar()
tp(env, e, a, emptySubst)(a)
}
}
object predefined {
- val booleanType = Tycon("Boolean", List());
- val intType = Tycon("Int", List());
- def listType(t: Type) = Tycon("List", List(t));
+ val booleanType = Tycon("Boolean", List())
+ val intType = Tycon("Int", List())
+ def listType(t: Type) = Tycon("List", List(t))
- private def gen(t: Type): typeInfer.TypeScheme = typeInfer.gen(List(), t);
- private val a = typeInfer.newTyvar();
+ private def gen(t: Type): typeInfer.TypeScheme = typeInfer.gen(List(), t)
+ private val a = typeInfer.newTyvar()
val env = List(
/*
Pair("true", gen(booleanType)),
@@ -148,24 +149,24 @@ object typeInfer {
)
}
- abstract class MiniMLParsers extends CharParsers {
+ mixin class MiniMLParsers extends CharParsers {
/** whitespace */
- def whitespace = rep{chr(' ') ||| chr('\t') ||| chr('\n')};
+ def whitespace = rep{chr(' ') ||| chr('\t') ||| chr('\n')}
/** A given character, possible preceded by whitespace */
- def wschr(ch: char) = whitespace &&& chr(ch);
+ def wschr(ch: char) = whitespace &&& chr(ch)
/** identifiers or keywords */
def id: Parser[String] =
for (
val c: char <- rep(chr(' ')) &&& chr(Character.isLetter);
val cs: List[char] <- rep(chr(Character.isLetterOrDigit))
- ) yield (c :: cs).mkString("", "", "");
+ ) yield (c :: cs).mkString("", "", "")
/** Non-keyword identifiers */
def ident: Parser[String] =
- for (val s <- id; s != "let" && s != "in") yield s;
+ for (val s <- id; s != "let" && s != "in") yield s
/** term = '\' ident '.' term | term1 {term1} | let ident "=" term in term */
def term: Parser[Term] =
@@ -188,7 +189,7 @@ object typeInfer {
( for (
val t <- term1;
val ts <- rep(term1))
- yield (t /: ts)((f, arg) => App(f, arg)) );
+ yield (t /: ts)((f, arg) => App(f, arg)) )
/** term1 = ident | '(' term ')' */
def term1: Parser[Term] =
@@ -206,39 +207,41 @@ object typeInfer {
for (
val t <- term;
val _ <- wschr(';'))
- yield t;
+ yield t
}
class ParseString(s: String) extends Parsers {
- type intype = int;
- val input = 0;
+ type intype = int
+ val input = 0
def any = new Parser[char] {
def apply(in: int): Parser[char]#Result =
- if (in < s.length()) Some(Pair(s charAt in, in + 1)) else None;
+ if (in < s.length()) Some(Pair(s charAt in, in + 1)) else None
}
}
def showType(e: Term): String =
try {
- typeInfer.typeOf(predefined.env, e).toString();
- } catch {
+ typeInfer.typeOf(predefined.env, e).toString()
+ }
+ catch {
case typeInfer.TypeError(msg) =>
- "\n cannot type: " + typeInfer.current +
- "\n reason: " + msg;
+ "\n cannot type: " + typeInfer.current +
+ "\n reason: " + msg
}
def main(args: Array[String]): unit =
Console.println(
if (args.length == 1) {
- val ps = new MiniMLParsers with ParseString(args(0));
+ val ps = new ParseString(args(0)) with MiniMLParsers
ps.all(ps.input) match {
case Some(Pair(term, _)) =>
"" + term + ": " + showType(term)
case None =>
- "syntax error"
+ "syntax error"
}
- } else "usage: java examples.typeinf <expr-string>"
- );
+ }
+ else
+ "usage: java examples.typeinf <expr-string>"
+ )
}
-