Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Remove docs/examples; they reside at scala/scala-dist

  • Loading branch information...
commit e55510607031aaf7b8473453f83c44a26c9b97e0 1 parent dc6dd58
@adriaanm adriaanm authored
Showing with 1 addition and 6,120 deletions.
  1. +0 −283 build.examples.xml
  2. +1 −6 build.xml
  3. +0 −131 docs/examples/actors/auction.scala
  4. +0 −37 docs/examples/actors/boundedbuffer.scala
  5. +0 −32 docs/examples/actors/channels.scala
  6. +0 −82 docs/examples/actors/fringe.scala
  7. +0 −47 docs/examples/actors/links.scala
  8. +0 −26 docs/examples/actors/looping.scala
  9. +0 −40 docs/examples/actors/message.scala
  10. +0 −61 docs/examples/actors/pingpong.scala
  11. +0 −114 docs/examples/actors/producers.scala
  12. +0 −15 docs/examples/actors/seq.scala
  13. +0 −46 docs/examples/boundedbuffer.scala
  14. +0 −54 docs/examples/computeserver.scala
  15. +0 −68 docs/examples/expressions/expressions-current.scala
  16. +0 −112 docs/examples/fors.scala
  17. +0 −17 docs/examples/futures.scala
  18. +0 −22 docs/examples/gadts.scala
  19. +0 −28 docs/examples/iterators.scala
  20. +0 −55 docs/examples/jolib/Ref.scala
  21. +0 −58 docs/examples/jolib/parallelOr.scala
  22. +0 −187 docs/examples/maps.scala
  23. +0 −86 docs/examples/monads/callccInterpreter.scala
  24. +0 −55 docs/examples/monads/directInterpreter.scala
  25. +0 −86 docs/examples/monads/errorInterpreter.scala
  26. +0 −75 docs/examples/monads/simpleInterpreter.scala
  27. +0 −86 docs/examples/monads/stateInterpreter.scala
  28. +0 −64 docs/examples/oneplacebuffer.scala
  29. +0 −57 docs/examples/parsing/ArithmeticParser.scala
  30. +0 −70 docs/examples/parsing/ArithmeticParsers.scala
  31. +0 −44 docs/examples/parsing/JSON.scala
  32. +0 −33 docs/examples/parsing/ListParser.scala
  33. +0 −30 docs/examples/parsing/ListParsers.scala
  34. +0 −52 docs/examples/parsing/MiniML.scala
  35. +0 −34 docs/examples/parsing/lambda/Main.scala
  36. +0 −68 docs/examples/parsing/lambda/TestParser.scala
  37. +0 −86 docs/examples/parsing/lambda/TestSyntax.scala
  38. +0 −1  docs/examples/parsing/lambda/test/test-01.kwi
  39. +0 −1  docs/examples/parsing/lambda/test/test-02.kwi
  40. +0 −1  docs/examples/parsing/lambda/test/test-03.kwi
  41. +0 −1  docs/examples/parsing/lambda/test/test-04.kwi
  42. +0 −1  docs/examples/parsing/lambda/test/test-05.kwi
  43. +0 −1  docs/examples/parsing/lambda/test/test-06.kwi
  44. +0 −1  docs/examples/parsing/lambda/test/test-07.kwi
  45. +0 −1  docs/examples/parsing/lambda/test/test-08.kwi
  46. +0 −36 docs/examples/patterns.scala
  47. +0 −77 docs/examples/pilib/elasticBuffer.scala
  48. +0 −186 docs/examples/pilib/handover.scala
  49. +0 −172 docs/examples/pilib/mobilePhoneProtocol.scala
  50. +0 −89 docs/examples/pilib/piNat.scala
  51. +0 −329 docs/examples/pilib/rwlock.scala
  52. +0 −150 docs/examples/pilib/scheduler.scala
  53. +0 −72 docs/examples/pilib/semaphore.scala
  54. +0 −67 docs/examples/pilib/twoPlaceBuffer.scala
  55. +0 −11 docs/examples/plugintemplate/.classpath
  56. +0 −18 docs/examples/plugintemplate/.project
  57. +0 −265 docs/examples/plugintemplate/build.xml
  58. +0 −68 docs/examples/plugintemplate/doc/README
  59. +0 −8 docs/examples/plugintemplate/doc/examples/plugintemplate/examples/BasicExample.scala
  60. +0 −1  docs/examples/plugintemplate/lib/scalatest.jar.desired.sha1
  61. +0 −4 docs/examples/plugintemplate/misc/scalac-plugin.xml
  62. +0 −10 docs/examples/plugintemplate/plugin.properties
  63. +0 −61 docs/examples/plugintemplate/src/plugintemplate/PluginProperties.scala
  64. +0 −20 docs/examples/plugintemplate/src/plugintemplate/TemplateAnnotationChecker.scala
  65. +0 −35 docs/examples/plugintemplate/src/plugintemplate/TemplateComponent.scala
  66. +0 −79 docs/examples/plugintemplate/src/plugintemplate/TemplateInfoTransformComponent.scala
  67. +0 −52 docs/examples/plugintemplate/src/plugintemplate/TemplatePlugin.scala
  68. +0 −58 docs/examples/plugintemplate/src/plugintemplate/TemplateTransformComponent.scala
  69. +0 −32 docs/examples/plugintemplate/src/plugintemplate/TemplateTraverseComponent.scala
  70. +0 −44 docs/examples/plugintemplate/src/plugintemplate/standalone/Main.scala
  71. +0 −36 docs/examples/plugintemplate/src/plugintemplate/standalone/PluginRunner.scala
  72. +0 −14 docs/examples/plugintemplate/test/plugintemplate/PluginPropertiesSuite.scala
  73. +0 −22 docs/examples/plugintemplate/test/plugintemplate/TemplatePluginSuite.scala
  74. +0 −48 docs/examples/sort.scala
  75. +0 −22 docs/examples/sort1.scala
  76. +0 −25 docs/examples/sort2.scala
  77. +0 −24 docs/examples/swing/ButtonApp.scala
  78. +0 −42 docs/examples/swing/CelsiusConverter.scala
  79. +0 −36 docs/examples/swing/CelsiusConverter2.scala
  80. +0 −86 docs/examples/swing/ComboBoxes.scala
  81. +0 −30 docs/examples/swing/CountButton.scala
  82. +0 −176 docs/examples/swing/Dialogs.scala
  83. +0 −64 docs/examples/swing/GridBagDemo.scala
  84. +0 −13 docs/examples/swing/HelloWorld.scala
  85. +0 −19 docs/examples/swing/LabelTest.scala
  86. +0 −53 docs/examples/swing/LinePainting.scala
  87. +0 −17 docs/examples/swing/ListViewDemo.scala
  88. +0 −18 docs/examples/swing/SimpleApplet.scala
  89. +0 −29 docs/examples/swing/SwingApp.scala
  90. +0 −96 docs/examples/swing/TableSelection.scala
  91. +0 −147 docs/examples/swing/UIDemo.scala
  92. BIN  docs/examples/swing/images/banana.jpg
  93. BIN  docs/examples/swing/images/margarita1.jpg
  94. BIN  docs/examples/swing/images/margarita2.jpg
  95. BIN  docs/examples/swing/images/rose.jpg
  96. +0 −167 docs/examples/tcpoly/collection/HOSeq.scala
  97. +0 −69 docs/examples/tcpoly/monads/Monads.scala
  98. +0 −253 docs/examples/typeinf.scala
  99. +0 −26 docs/examples/xml/phonebook/embeddedBook.scala
  100. +0 −38 docs/examples/xml/phonebook/phonebook.scala
  101. +0 −21 docs/examples/xml/phonebook/phonebook1.scala
  102. +0 −25 docs/examples/xml/phonebook/phonebook2.scala
  103. +0 −81 docs/examples/xml/phonebook/phonebook3.scala
  104. +0 −24 docs/examples/xml/phonebook/verboseBook.scala
View
283 build.examples.xml
@@ -1,283 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-
-<project name="scala-examples" default="build">
-
- <description>
- I am SABBUS for ${ant.project.name}, the build system for the Scala compiler
- and core library. Please check the 'docs/README' file for more information
- about me.
- </description>
-
- <echo level="info" message="Running SABBUS for ${ant.project.name}..."/>
-
-<!-- ===========================================================================
-PROPERTIES
-============================================================================ -->
-
- <property environment="env"/>
-
- <!-- Prevents system classpath from being used -->
- <property name="build.sysclasspath" value="ignore"/>
-
- <!-- Base properties -->
- <property name="src.dir" value="${basedir}/docs"/>
- <property name="src.examples.dir" value="${src.dir}/examples"/>
- <property name="lib.dir" value="${basedir}/lib"/>
- <!-- User properties -->
- <property file="${basedir}/build.examples.properties"/>
- <!-- Location of pre-compiled libraries properties -->
- <property name="scala.lib.jar" value="${lib.dir}/scala-library.jar"/>
- <property name="scala.comp.jar" value="${lib.dir}/scala-compiler.jar"/>
- <property name="fjbg.name" value="fjbg.jar"/>
- <property name="fjbg.jar" value="${lib.dir}/${fjbg.name}"/>
- <property name="msil.name" value="msil.jar"/>
- <property name="msil.jar" value="${lib.dir}/${msil.name}"/>
- <property name="ant.jar" value="${ant.home}/lib/ant.jar"/>
- <property name="ant-contrib.jar" value="${lib.dir}/ant/ant-contrib.jar"/>
- <!-- -->
- <property name="build.dir" value="${basedir}/build"/>
- <property name="build.examples.dir" value="${build.dir}/examples"/>
- <!-- tbd -->
- <property name="excludes.compile"
- value="**/*current.*,**/parsers2.*,**/typeinf.*"/>
- <property name="excludes.run"
- value="**/Parsers.*"/>
-
-<!-- ===========================================================================
-INITIALISATION
-============================================================================ -->
-
- <target name="init" unless="init.avail">
- <tstamp prefix="start">
- <format
- property="human-time"
- pattern="EEEE, d MMMM yyyy, HH:mm:ss (zz)"
- />
- </tstamp>
- <!-- Testing if everything is in place -->
- <echo level="verbose" message="scala.lib.jar=${scala.lib.jar}"/>
- <fail message="Scala library in '${lib.dir}/' is not available">
- <condition><not><and>
- <available
- classname="scala.Predef"
- classpath="${scala.lib.jar}"
- />
- <available
- classname="scala.collection.immutable.List"
- classpath="${scala.lib.jar}"
- />
- <available
- classname="scala.runtime.ObjectRef"
- classpath="${scala.lib.jar}"
- />
- </and></not></condition>
- </fail>
- <echo level="verbose" message="scala.comp.jar=${scala.comp.jar}"/>
- <fail message="Scala compiler in '${lib.dir}/' is not available">
- <condition><not>
- <available
- classname="scala.tools.ant.Scalac"
- classpath="${scala.comp.jar}:${scala.lib.jar}"
- />
- </not></condition>
- </fail>
- <echo level="verbose" message="fjbg.jar=${fjbg.jar}"/>
- <fail message="FJBG library in '${lib.dir}/' is not available">
- <condition><not>
- <available
- classname="ch.epfl.lamp.fjbg.JCode"
- classpath="${fjbg.jar}"
- />
- </not></condition>
- </fail>
- <echo level="verbose" message="msil.jar=${msil.jar}"/>
- <fail message="MSIL library in '${lib.dir}/' is not available">
- <condition><not>
- <available
- classname="ch.epfl.lamp.compiler.msil.MemberInfo"
- classpath="${msil.jar}"
- />
- </not></condition>
- </fail>
- <echo level="verbose" message="ant.jar=${ant.jar}"/>
- <echo level="verbose" message="ant-contrib.jar=${ant-contrib.jar}"/>
- <fail message="Additional Ant tasks in '${lib.dir}/' is not available">
- <condition><not>
- <available
- classname="net.sf.antcontrib.AntContribVersion"
- classpath="${ant-contrib.jar}"
- />
- </not></condition>
- </fail>
- <!-- Creating class-pathes -->
- <path id="common.classpath">
- <pathelement location="${fjbg.jar}"/>
- <pathelement location="${msil.jar}"/>
- </path>
- <path id="scala.classpath">
- <pathelement location="${scala.lib.jar}"/>
- <pathelement location="${scala.comp.jar}"/>
- <path refid="common.classpath"/>
- </path>
- <!-- Creating boot-level tasks -->
- <taskdef resource="net/sf/antcontrib/antlib.xml">
- <classpath>
- <pathelement location="${ant-contrib.jar}"/>
- </classpath>
- </taskdef>
- <!-- Finding out what system architecture is being used -->
- <condition property="os.win">
- <os family="windows"/>
- </condition>
- <if><isset property="os.win"/>
- <then>
- <exec
- executable="cygpath"
- vmlauncher="no"
- errorproperty="cygpath.err"
- outputproperty="cygpath.out"
- >
- <arg value="--windir"/>
- </exec>
- <condition property="os.cygwin">
- <equals arg1="${cygpath.err}" arg2=""/>
- </condition>
- </then>
- </if>
- <condition property="os.unix">
- <or>
- <os family="unix"/>
- <os family="mac"/>
- <isset property="os.cygwin"/>
- </or>
- </condition>
- <if><isset property="os.cygwin"/>
- <then><property name="os.type" value="Cygwin"/></then>
- <elseif><isset property="os.win"/>
- <then><property name="os.type" value="Windows"/></then>
- </elseif>
- <elseif><isset property="os.unix"/>
- <then><property name="os.type" value="UNIX"/></then>
- </elseif>
- <else>
- <fail>System environment could not be determined</fail>
- </else>
- </if>
- <echo
- level="info"
- message="OS: ${os.type} (${os.name} ${os.arch} ${os.version});"
- />
- <echo
- level="info"
- message="Java: ${java.version} ('${java.home}');"
- />
- <echo
- level="info"
- message="JVM: ${java.vm.name} ${java.vm.version};"
- />
- <echo
- level="info"
- message="Ant: ${ant.version}."
- />
- <property name="init.avail" value="yes"/>
- </target>
-
- <target name="setup" depends="init">
- <!-- Creating boot-level tasks -->
- <taskdef
- name="scalac"
- classname="scala.tools.ant.Scalac"
- classpathref="scala.classpath"
- />
- <property name="init.avail" value="yes"/>
- </target>
-
-<!-- ===========================================================================
-BUILD
-============================================================================ -->
-
- <target name="build" depends="setup">
- <mkdir dir="${build.dir}"/>
- <echo level="verbose">src.dir=${src.dir}</echo>
- <pathconvert property="list" pathsep=",">
- <path>
- <fileset
- dir="${src.dir}"
- includes="examples/*.scala"
- excludes="${excludes.compile}"
- />
- </path>
- <mapper>
- <globmapper from="${src.dir}/*" to="*"/>
- </mapper>
- </pathconvert>
- <for list="${list}" param="file">
- <sequential>
- <scalac srcdir="${src.dir}"
- destdir="${build.dir}" deprecation="true">
- <classpath>
- <pathelement location="${scala.lib.jar}"/>
- <pathelement location="${build.dir}"/>
- </classpath>
- <include name="@{file}"/>
- </scalac>
- </sequential>
- </for>
- </target>
-
-<!-- ===========================================================================
-RUN
-============================================================================ -->
-
- <target name="run" depends="build">
- <pathconvert property="list" pathsep=",">
- <path>
- <fileset
- dir="${src.dir}"
- includes="examples/*.scala"
- excludes="${excludes.run}"
- />
- </path>
- <mapper>
- <globmapper from="${src.dir}/*" to="*"/>
- </mapper>
- </pathconvert>
- <for list="${list}" param="file">
- <sequential>
- <var name="classname" unset="true"/>
- <basename property="classname" file="@{file}" suffix=".scala"/>
- <echo>Executing Scala program examples.${classname}..</echo>
- <java classname="examples.${classname}" fork="true"
- output="${build.examples.dir}/${classname}.log"
- error="${build.examples.dir}/${classname}.log"
- append="true">
- <classpath>
- <pathelement location="${scala.lib.jar}"/>
- <pathelement location="${build.dir}"/>
- </classpath>
- </java>
- </sequential>
- </for>
- </target>
-
-<!-- ===========================================================================
-CLEAN
-============================================================================ -->
-
- <macrodef name="remove">
- <attribute name="dir"/>
- <sequential>
- <delete
- dir="@{dir}"
- includeemptydirs="yes"
- quiet="yes"
- failonerror="no"
- />
- </sequential>
- </macrodef>
-
- <target name="clean" description="Removes all build examples">
- <remove dir="${build.examples.dir}"/>
- </target>
-
-</project>
View
7 build.xml
@@ -1868,12 +1868,7 @@ TODO:
<copy toDir="${dist.dir}/doc/scala-devel-docs/api">
<fileset dir="${build-docs.dir}/library"/>
</copy>
- <mkdir dir="${dist.dir}/doc/scala-devel-docs/examples"/>
- <copy toDir="${dist.dir}/doc/scala-devel-docs/examples">
- <fileset dir="${docs.dir}/examples">
- <exclude name="**/*.desired.sha1"/>
- </fileset>
- </copy>
+
<mkdir dir="${dist.dir}/doc/scala-devel-docs/tools"/>
<copy toDir="${dist.dir}/doc/scala-devel-docs/tools">
<fileset dir="${build-docs.dir}/manual/html"/>
View
131 docs/examples/actors/auction.scala
@@ -1,131 +0,0 @@
-package examples.actors
-
-import java.util.Date
-
-import scala.actors._
-import scala.actors.Actor._
-
-/** A simple demonstrator program implementing an online auction service
- * The example uses the actor abstraction defined in the API of
- * package scala.actors.
- */
-
-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 object 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 object AuctionFailed extends AuctionReply // failed with no bids
-case object AuctionOver extends AuctionReply // bidding is closed
-
-class AuctionActor(seller: Actor, minBid: Int, closing: Date) extends Actor {
- val timeToShutdown = 3000 // msec
- val bidIncrement = 10
-
- def act() {
- var maxBid = minBid - bidIncrement
- var maxBidder: Actor = null
-
- loop {
- reactWithin (closing.getTime() - new Date().getTime()) {
-
- case Offer(bid, client) =>
- if (bid >= maxBid + bidIncrement) {
- if (maxBid >= minBid)
- maxBidder ! BeatenOffer(bid)
- maxBid = bid
- maxBidder = client
- client ! BestOffer
- }
- else
- client ! BeatenOffer(maxBid)
-
- case Inquire(client) =>
- client ! Status(maxBid, closing)
-
- case TIMEOUT =>
- if (maxBid >= minBid) {
- val reply = AuctionConcluded(seller, maxBidder)
- maxBidder ! reply
- seller ! reply
- } else {
- seller ! AuctionFailed
- }
- reactWithin(timeToShutdown) {
- case Offer(_, client) => client ! AuctionOver
- case TIMEOUT => exit()
- }
-
- }
- }
- }
-}
-
-object auction {
-
- val random = new scala.util.Random
-
- val minBid = 100
- val closing = new Date(new Date().getTime() + 4000)
-
- val seller = Actor.actor { }
- val auction = new AuctionActor(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 max: Int = _
- var current: Int = 0
- def act() {
- log("started")
- auction ! Inquire(this)
- receive {
- case Status(maxBid, _) =>
- log("status(" + maxBid + ")")
- max = maxBid
- }
- loop {
- if (max >= top) {
- log("too high for me")
- }
- else if (current < max) {
- current = max + increment
- Thread.sleep(1 + random.nextInt(1000))
- auction ! Offer(current, this)
- }
-
- reactWithin(3000) {
- case BestOffer =>
- log("bestOffer(" + current + ")")
-
- case BeatenOffer(maxBid) =>
- log("beatenOffer(" + maxBid + ")")
- max = maxBid
-
- case AuctionConcluded(seller, maxBidder) =>
- log("auctionConcluded"); exit()
-
- case AuctionOver =>
- log("auctionOver"); exit()
-
- case TIMEOUT =>
- exit()
- }
- }
- }
- }
-
- def main(args: Array[String]) {
- seller.start()
- auction.start()
- client(1, 20, 200).start()
- client(2, 10, 300).start()
- }
-
-}
View
37 docs/examples/actors/boundedbuffer.scala
@@ -1,37 +0,0 @@
-package examples.actors
-
-import scala.actors.Actor._
-
-object boundedbuffer {
- class BoundedBuffer[T](N: Int)(implicit m: Manifest[T]) {
- private case class Put(x: T)
- private case object Get
- private case object Stop
-
- private val buffer = actor {
- val buf = new Array[T](N)
- var in, out, n = 0
- loop {
- react {
- case Put(x) if n < N =>
- buf(in) = x; in = (in + 1) % N; n += 1; reply()
- case Get if n > 0 =>
- val r = buf(out); out = (out + 1) % N; n -= 1; reply(r)
- case Stop =>
- reply(); exit("stopped")
- }
- }
- }
-
- def put(x: T) { buffer !? Put(x) }
- def get: T = (buffer !? Get).asInstanceOf[T]
- def stop() { buffer !? Stop }
- }
-
- def main(args: Array[String]) {
- val buf = new BoundedBuffer[Int](1)
- buf.put(42)
- println("" + buf.get)
- buf.stop()
- }
-}
View
32 docs/examples/actors/channels.scala
@@ -1,32 +0,0 @@
-package examples.actors
-
-import scala.actors._
-import scala.actors.Actor._
-
-object channels extends Application {
- case class Msg(ch1: Channel[Int], ch2: Channel[String])
-
- val a = actor {
- val Ch1 = new Channel[Int]
- val Ch2 = new Channel[String]
-
- b ! Msg(Ch1, Ch2)
-
- val ICh1 = Ch1.asInstanceOf[InputChannel[Int]]
- val ICh2 = Ch2.asInstanceOf[InputChannel[String]]
-
- react {
- case ICh1 ! (x: Int) =>
- val r = x + 21
- println("result: "+r)
- case ICh2 ! y =>
- println("received: "+y)
- }
- }
-
- val b = actor {
- react {
- case Msg(ch1, ch2) => ch1 ! 21
- }
- }
-}
View
82 docs/examples/actors/fringe.scala
@@ -1,82 +0,0 @@
-package examples.actors
-
-import scala.actors.Actor._
-import scala.actors.{Channel, OutputChannel}
-
-/**
- @author Philipp Haller
- @version 1.1, 09/21/2007
- */
-object fringe extends Application {
-
- abstract class Tree
- case class Node(left: Tree, right: Tree) extends Tree
- case class Leaf(v: Int) extends Tree
-
- case class CompareFringe(t1: Tree, t2: Tree)
- case class ComputeFringe(t1: Tree, atoms: OutputChannel[Option[Leaf]])
- case class Equal(atom1: Option[Leaf], atom2: Option[Leaf])
- case class Extract(tree: Tree)
-
- val comparator = actor {
- val extractor1 = actor(extractorBehavior())
- val extractor2 = actor(extractorBehavior())
- val ch1 = new Channel[Option[Leaf]]
- val ch2 = new Channel[Option[Leaf]]
- loop {
- react {
- case CompareFringe(tree1, tree2) =>
- extractor1 ! ComputeFringe(tree1, ch1)
- extractor2 ! ComputeFringe(tree2, ch2)
- self ! Equal(ch1.?, ch2.?)
-
- case Equal(atom1, atom2) =>
- if (atom1 == atom2) atom1 match {
- case None =>
- println("same fringe")
- exit()
- case _ =>
- self ! Equal(ch1.?, ch2.?)
- } else {
- println("fringes differ")
- exit()
- }
- }
- }
- }
-
- val extractorBehavior = () => {
- var output: OutputChannel[Option[Leaf]] = null
- loop {
- react {
- case ComputeFringe(tree, leafSink) =>
- output = leafSink
- self ! Extract(tree)
-
- case Extract(tree) => tree match {
- case atom @ Leaf(_) =>
- output ! Some(atom)
- sender ! 'Continue
-
- case Node(left, right) =>
- val outer = self
- val outerCont = sender
- val cont = actor {
- react {
- case 'Continue =>
- outer.send(Extract(right), outerCont)
- }
- }
- self.send(Extract(left), cont)
- }
-
- case 'Continue =>
- output ! None
- exit()
- }
- }
- }
-
- comparator ! CompareFringe(Node(Leaf(5), Node(Leaf(7), Leaf(3))),
- Node(Leaf(5), Node(Leaf(7), Leaf(3))))
-}
View
47 docs/examples/actors/links.scala
@@ -1,47 +0,0 @@
-package examples.actors
-
-import scala.actors.{Actor, Exit}
-import scala.actors.Actor._
-
-object links extends Application {
-
- case object Stop
-
- actor {
- val start = link(p(2))
- start ! Stop
- }
-
- def p(n: Int): Actor =
- if (n == 0) top1()
- else top(p(n-1), n)
-
- def top(a: Actor, n: Int): Actor = actor {
- println("starting actor " + n + " (" + self + ")")
- self.trapExit = true
- link(a)
- loop {
- receive {
- case ex @ Exit(from, reason) =>
- println("Actor " + n + " received " + ex)
- exit('finished)
- case any => {
- println("Actor " + n + " received " + any)
- a ! any
- }
- }
- }
- }
-
- def top1(): Actor = actor {
- println("starting last actor" + " (" + self + ")")
- receive {
- case Stop =>
- println("Last actor now exiting")
- exit('abnormal)
- case any =>
- println("Last actor received " + any)
- top1()
- }
- }
-}
View
26 docs/examples/actors/looping.scala
@@ -1,26 +0,0 @@
-package examples.actors
-
-import scala.actors.Actor._
-
-object looping extends Application {
- case object A
-
- val a = actor {
- var cnt = 0
- loop {
- react {
- case A =>
- cnt += 1
- if (cnt % 2 != 0) continue
- if (cnt < 10)
- println("received A")
- else {
- println("received last A")
- exit()
- }
- }
- }
- }
-
- for (i <- 0 until 10) a ! A
-}
View
40 docs/examples/actors/message.scala
@@ -1,40 +0,0 @@
-package examples.actors
-
-import scala.actors.{Actor, Scheduler}
-import scala.actors.Actor._
-import scala.actors.scheduler.SingleThreadedScheduler
-
-object message {
- def main(args: Array[String]) {
- val n = try { args(0).toInt }
- catch {
- case _ =>
- println("Usage: examples.actors.message <n>")
- Predef.exit
- }
- val nActors = 500
- val finalSum = n * nActors
- Scheduler.impl = new SingleThreadedScheduler
-
- def beh(next: Actor, sum: Int) {
- react {
- case value: Int =>
- val j = value + 1; val nsum = sum + j
- if (next == null && nsum >= n * j)
- println(nsum)
- else {
- if (next != null) next ! j
- if (nsum < n * j) beh(next, nsum)
- }
- }
- }
-
- def actorChain(i: Int, a: Actor): Actor =
- if (i > 0) actorChain(i-1, actor(beh(a, 0))) else a
-
- val firstActor = actorChain(nActors, null)
- var i = n; while (i > 0) { firstActor ! 0; i -= 1 }
-
- Scheduler.shutdown()
- }
-}
View
61 docs/examples/actors/pingpong.scala
@@ -1,61 +0,0 @@
-package examples.actors
-
-import scala.actors.Actor
-import scala.actors.Actor._
-
-case object Ping
-case object Pong
-case object Stop
-
-/**
- * Ping pong example.
- *
- * @author Philipp Haller
- * @version 1.1
- */
-object pingpong extends Application {
- val pong = new Pong
- val ping = new Ping(100000, pong)
- ping.start
- pong.start
-}
-
-class Ping(count: Int, pong: Actor) extends Actor {
- def act() {
- var pingsLeft = count - 1
- pong ! Ping
- loop {
- react {
- case Pong =>
- if (pingsLeft % 1000 == 0)
- println("Ping: pong")
- if (pingsLeft > 0) {
- pong ! Ping
- pingsLeft -= 1
- } else {
- println("Ping: stop")
- pong ! Stop
- exit()
- }
- }
- }
- }
-}
-
-class Pong extends Actor {
- def act() {
- var pongCount = 0
- loop {
- react {
- case Ping =>
- if (pongCount % 1000 == 0)
- println("Pong: ping "+pongCount)
- sender ! Pong
- pongCount += 1
- case Stop =>
- println("Pong: stop")
- exit()
- }
- }
- }
-}
View
114 docs/examples/actors/producers.scala
@@ -1,114 +0,0 @@
-package examples.actors
-
-import scala.actors.Actor
-import scala.actors.Actor._
-
-abstract class Producer[T] {
-
- /** A signal that the next value should be produced. */
- private val Next = new Object
-
- /** A label for an undefined state of the iterators. */
- private val Undefined = new Object
-
- /** A signal to stop the coordinator. */
- private val Stop = new Object
-
- protected def produce(x: T) {
- coordinator ! Some(x)
- receive { case Next => }
- }
-
- protected def produceValues: Unit
-
- def iterator = new Iterator[T] {
- private var current: Any = Undefined
- private def lookAhead = {
- if (current == Undefined) current = coordinator !? Next
- current
- }
-
- def hasNext: Boolean = lookAhead match {
- case Some(x) => true
- case None => { coordinator ! Stop; false }
- }
-
- def next: T = lookAhead match {
- case Some(x) => current = Undefined; x.asInstanceOf[T]
- }
- }
-
- private val coordinator: Actor = actor {
- loop {
- react {
- case Next =>
- producer ! Next
- reply {
- receive { case x: Option[_] => x }
- }
- case Stop =>
- exit('stop)
- }
- }
- }
-
- private val producer: Actor = actor {
- receive {
- case Next =>
- produceValues
- coordinator ! None
- }
- }
-}
-
-object producers extends Application {
-
- class Tree(val left: Tree, val elem: Int, val right: Tree)
- def node(left: Tree, elem: Int, right: Tree): Tree = new Tree(left, elem, right)
- def node(elem: Int): Tree = node(null, elem, null)
-
- def tree = node(node(node(3), 4, node(6)), 8, node(node(9), 10, node(11)))
-
- class PreOrder(n: Tree) extends Producer[Int] {
- def produceValues = traverse(n)
- def traverse(n: Tree) {
- if (n != null) {
- produce(n.elem)
- traverse(n.left)
- traverse(n.right)
- }
- }
- }
-
- class PostOrder(n: Tree) extends Producer[Int] {
- def produceValues = traverse(n)
- def traverse(n: Tree) {
- if (n != null) {
- traverse(n.left)
- traverse(n.right)
- produce(n.elem)
- }
- }
- }
-
- class InOrder(n: Tree) extends Producer[Int] {
- def produceValues = traverse(n)
- def traverse(n: Tree) {
- if (n != null) {
- traverse(n.left)
- produce(n.elem)
- traverse(n.right)
- }
- }
- }
-
- actor {
- print("PreOrder:")
- for (x <- new PreOrder(tree).iterator) print(" "+x)
- print("\nPostOrder:")
- for (x <- new PostOrder(tree).iterator) print(" "+x)
- print("\nInOrder:")
- for (x <- new InOrder(tree).iterator) print(" "+x)
- print("\n")
- }
-}
View
15 docs/examples/actors/seq.scala
@@ -1,15 +0,0 @@
-package examples.actors
-
-object seq extends Application {
- import scala.actors.Actor._
- val a = actor {
- { react {
- case 'A => println("received 1st message")
- }; ()
- } andThen react {
- case 'A => println("received 2nd message")
- }
- }
- a ! 'A
- a ! 'A
-}
View
46 docs/examples/boundedbuffer.scala
@@ -1,46 +0,0 @@
-package examples
-
-object boundedbuffer {
-
- import concurrent.ops._
-
- class BoundedBuffer[A](N: Int)(implicit m: ClassManifest[A]) {
- 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 += 1
- if (n == 1) notifyAll()
- }
-
- def get: A = synchronized {
- await (n != 0)
- val x = elems(out); out = (out + 1) % N ; n -= 1
- if (n == N - 1) notifyAll()
- x
- }
- }
-
- def kill(delay: Int) = new java.util.Timer().schedule(
- new java.util.TimerTask {
- override def run() = {
- println("[killed]")
- System.exit(0)
- }
- },
- delay) // in milliseconds
-
- def main(args: Array[String]) {
- val buf = new BoundedBuffer[String](10)
- var cnt = 0
- def produceString = { cnt += 1; cnt.toString() }
- def consumeString(ss: String) = println(ss)
- spawn { while (true) { val ssss = produceString; buf.put(ssss) } }
- spawn { while (true) { val s = buf.get; consumeString(s) } }
- kill(1000)
- }
-
-}
View
54 docs/examples/computeserver.scala
@@ -1,54 +0,0 @@
-package examples
-
-import concurrent._, concurrent.ops._
-
-class ComputeServer(n: Int) {
-
- private trait Job {
- type t
- def task: t
- def ret(x: t): Unit
- }
-
- private val openJobs = new Channel[Job]()
-
- private def processor(i: Int) {
- while (true) {
- val job = openJobs.read
- println("read a job")
- job.ret(job.task)
- }
- }
-
- def future[a](p: => a): () => a = {
- val reply = new SyncVar[a]()
- openJobs.write{
- new Job {
- type t = a
- def task = p
- def ret(x: a) = reply.set(x)
- }
- }
- () => reply.get
- }
-
- //spawn(replicate(0, n) { processor })
- spawn((0 until n).par foreach { processor })
-}
-
-object computeserver extends App {
-
- def kill(delay: Int) = new java.util.Timer().schedule(
- new java.util.TimerTask {
- override def run() = {
- println("[killed]")
- sys exit 0
- }
- },
- delay) // in milliseconds
-
- val server = new ComputeServer(1)
- val f = server.future(42)
- println(f())
- kill(10000)
-}
View
68 docs/examples/expressions/expressions-current.scala
@@ -1,68 +0,0 @@
-package examples.expressions
-
-class Ref[a](var elem:a) {}
-
-abstract class Lang {
- trait Visitor {
- def caseNum(n: int): unit
- }
-
- abstract class Exp {
- def visit(v: visitor): unit
- }
-
- type visitor <: Visitor
-
- class Num(n: int) extends Exp {
- def visit(v: visitor): unit = v.caseNum(n)
- }
-
- class Eval(result: Ref[int]) requires visitor extends Visitor {
- def caseNum(n: int) = result.elem = n
- }
-}
-
-abstract class Lang2 extends Lang {
- trait Visitor2 extends Visitor {
- def casePlus(left: Exp, right: Exp): unit
- }
-
- type visitor <: Visitor2
-
- class Plus(l: Exp, r: Exp) extends Exp {
- def visit(v: visitor): unit = v.casePlus(l, r)
- }
-
- // class Eval2(result: Ref[int]): visitor extends Eval(result) with Visitor2 {
- class Eval2(result: Ref[int]) requires visitor extends Eval(result) with Visitor2 {
- def casePlus(l: Exp, r: Exp) =
- result.elem = { l.visit(this); result.elem } + { r.visit(this); result.elem }
- }
-
- class Show2(result: Ref[String]) requires visitor extends Visitor2 {
- def caseNum(n: int) = result.elem = n.toString()
- def casePlus(l: Exp, r: Exp) =
- result.elem =
- "(" + { l.visit(this); result.elem } +
- "+" + { r.visit(this); result.elem } + ")"
- }
-}
-
-object Main {
- def main(args: Array[String]): unit = {
- //val l1 = new Lang { type visitor = Visitor } // not yet implemented
- object l1 extends Lang { type visitor = Visitor } // workaround
- val e1: l1.Exp = new l1.Num(42)
- val iref = new Ref(0)
- Console.println("eval: " + { e1.visit(new l1.Eval(iref)); iref.elem })
-
- //val l2 = new Lang2 { type visitor = Visitor2 } // not yet implemented
- object l2 extends Lang2 { type visitor = Visitor2 } // workaround
- val e2: l2.Exp = new l2.Plus(new l2.Num(5), new l2.Num(37))
- val sref = new Ref("")
- Console.println("eval: " + { e2.visit(new l2.Eval2(iref)); iref.elem })
- Console.println("show: " + { e2.visit(new l2.Show2(sref)); sref.elem })
- e1.visit(new l1.Eval(iref))
- e2.visit(new l2.Show2(sref))
- }
-}
View
112 docs/examples/fors.scala
@@ -1,112 +0,0 @@
-package examples
-
-import scala.xml._
-
-
-object fors {
-
- val e = Node.NoAttributes
-
- class Person(_name: String, _age: Int) {
- val name = _name
- val age = _age
- }
-
- def printOlderThan20(xs: Seq[Person]): Iterator[String] =
- printOlderThan20(xs.iterator)
-
- def printOlderThan20(xs: Iterator[Person]): Iterator[String] =
- for (p <- xs if p.age > 20) yield p.name
-
- val persons = List(
- new Person("John", 40),
- new Person("Richard", 68)
- )
-
- def divisors(n: Int): List[Int] =
- for (i <- List.range(1, n+1) if n % i == 0) yield i
-
- def isPrime(n: Int) = divisors(n).length == 2
-
- def findNums(n: Int): Iterable[(Int, Int)] =
- for (i <- 1 until n;
- j <- 1 until (i-1);
- if isPrime(i+j)) yield (i, j)
-
- def sum(xs: List[Double]): Double =
- xs.foldLeft(0.0) { (x, y) => x + y }
-
- def scalProd(xs: List[Double], ys: List[Double]) =
- sum(for((x, y) <- xs zip ys) yield x * y)
-
- type Lst = List[Any]
-
- val prefix = null
- val scope = TopScope
-
- val books = List(
- Elem(prefix, "book", e, scope,
- Elem(prefix, "title", e, scope,
- Text("Structure and Interpretation of Computer Programs")),
- Elem(prefix, "author", e, scope,
- Text("Abelson, Harald")),
- Elem(prefix, "author", e, scope,
- Text("Sussman, Gerald J."))),
- Elem(prefix, "book", e, scope,
- Elem(prefix, "title", e, scope,
- Text("Principles of Compiler Design")),
- Elem(prefix, "author", e, scope,
- Text("Aho, Alfred")),
- Elem(prefix, "author", e, scope,
- Text("Ullman, Jeffrey"))),
- Elem(prefix, "book", e, scope,
- Elem(prefix, "title", e, scope,
- Text("Programming in Modula-2")),
- Elem(prefix, "author", e, scope,
- Text("Wirth, Niklaus")))
- )
-
- def findAuthor(books: Lst) =
- for (Elem(_, "book", _, _, book @ _*) <- books;
- Elem(_, "title", _, _, Text(title)) <- book.toList;
- if (title indexOf "Program") >= 0;
- Elem(_, "author", _, _, Text(author)) <- List(book)) yield author
-
- for (Elem(_, "book", _, _, book @ _*) <- books;
- Elem(_, "author", _, _, Text(author)) <- book.toList;
- if author startsWith "Ullman";
- Elem(_, "title", _, _, Text(title)) <- List(book)) yield title
-
- removeDuplicates(
- for (Elem(_, "book", _, _, b1 @ _* ) <- books;
- Elem(_, "book", _, _, b2 @ _*) <- books;
- if b1 != b2;
- Elem(_, "author", _, _, Text(a1)) <- b1.toList;
- Elem(_, "author", _, _, Text(a2)) <- b2.toList;
- if a1 == a2) yield Pair(a1, a2))
-
- def removeDuplicates[a](xs: List[a]): List[a] =
- if (xs.isEmpty)
- xs
- else
- xs.head :: removeDuplicates(for (x <- xs.tail if x != xs.head) yield x)
-
- def main(args: Array[String]) {
- print("Persons over 20:")
- printOlderThan20(persons) foreach { x => print(" " + x) }
- println
-
- println("divisors(34) = " + divisors(34))
-
- print("findNums(15) =");
- findNums(15) foreach { x => print(" " + x); }
- println
-
- val xs = List(3.5, 5.0, 4.5)
- println("average(" + xs + ") = " + sum(xs) / xs.length)
-
- val ys = List(2.0, 1.0, 3.0)
- println("scalProd(" + xs + ", " + ys +") = " + scalProd(xs, ys))
- }
-
-}
View
17 docs/examples/futures.scala
@@ -1,17 +0,0 @@
-package examples
-
-import concurrent.ops._
-
-object futures {
- def someLengthyComputation = 1
- def anotherLengthyComputation = 2
- def f(x: Int) = x + x
- def g(x: Int) = x * x
-
- def main(args: Array[String]) {
- val x = future(someLengthyComputation)
- anotherLengthyComputation
- val y = f(x()) + g(x())
- println(y)
- }
-}
View
22 docs/examples/gadts.scala
@@ -1,22 +0,0 @@
-package examples
-
-object gadts extends Application {
-
- abstract class Term[T]
- case class Lit(x: Int) extends Term[Int]
- case class Succ(t: Term[Int]) extends Term[Int]
- case class IsZero(t: Term[Int]) extends Term[Boolean]
- case class If[T](c: Term[Boolean],
- t1: Term[T],
- t2: Term[T]) extends Term[T]
-
- def eval[T](t: Term[T]): T = t match {
- case Lit(n) => n
- case Succ(u) => eval(u) + 1
- case IsZero(u) => eval(u) == 0
- case If(c, u1, u2) => eval(if (eval(c)) u1 else u2)
- }
- println(
- eval(If(IsZero(Lit(1)), Lit(41), Succ(Lit(41)))))
-}
-
View
28 docs/examples/iterators.scala
@@ -1,28 +0,0 @@
-package examples
-
-object iterators {
-
- def Array(elems: Double*): Array[Double] = {
- val ar = new Array[Double](elems.length)
- for (i <- 0 until elems.length)
- ar(i) = elems(i)
- ar
- }
-
- def printArray(xs: Array[Double]) =
- xs.iterator foreach { x => println(x) }
-
- def findGreater(xs: Array[Double], limit: Double) =
- xs.iterator
- .zip(Iterator.from(0))
- .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)
- println("Elements greater than 3.0:")
- findGreater(ar, 3.0) foreach { x => Console.println(ar(x)) }
- }
-
-}
View
55 docs/examples/jolib/Ref.scala
@@ -1,55 +0,0 @@
-/* __ *\
-** ________ ___ / / ___ Scala API **
-** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL **
-** __\ \/ /__/ __ |/ /__/ __ | **
-** /____/\___/_/ |_/____/_/ | | **
-** |/ **
-\* */
-
-package examples.jolib;
-/*
-import concurrent.SyncVar;
-import concurrent.jolib._;
-
-class Ref[a](init: a) extends Join {
-
- object get extends Synchr[a](this) { case class C() extends SyncVar[a]; }
- object set extends Synchr[unit](this) { case class C(x: a) extends SyncVar[unit]; }
- object state extends Asynchr(this) { case class C(x: a); }
-
- rules (
- Pair(List(get, state), { case List(g @ get.C(), state.C(x) ) =>
- { g.set(x); state(state.C(x)) } }),
- Pair(List(set, state), { case List(s @ set.C(x), state.C(y) ) =>
- { s.set(()); state(state.C(x)) } })
- );
-
- state(state.C(init));
-
- def Get: a = get(get.C());
- def Set(x: a): unit = set(set.C(x));
-}
-*/
-object RefTest {
-
- def main(args: Array[String]) = {
- System.out.println("Started.");
-/*
- concurrent.ops.spawn({
- val r1 = new Ref(0);
- System.out.println("Reference r1 created.");
- System.out.println("Value r1 (first time) = " + r1.Get);
- r1.Set(42);
- System.out.println("Value r1 (second time) = " + r1.Get);
- });
- concurrent.ops.spawn({
- val r2 = new Ref(100);
- System.out.println("Reference r2 created.");
- System.out.println("Value r2 (first time) = " + r2.Get);
- r2.Set(89);
- System.out.println("Value r2 (second time) = " + r2.Get);
- });
-*/
- }
-
-}
View
58 docs/examples/jolib/parallelOr.scala
@@ -1,58 +0,0 @@
-/* __ *\
-** ________ ___ / / ___ Scala API **
-** / __/ __// _ | / / / _ | (c) 2003, LAMP/EPFL **
-** __\ \/ /__/ __ |/ /__/ __ | **
-** /____/\___/_/ |_/____/_/ | | **
-** |/ **
-\* */
-
-package examples.jolib;
-/*
-import concurrent.jolib._;
-import concurrent.SyncVar;
-
-/** Implementation in the join-calculus of a parallel OR. */
-object or extends Join {
-
- object res extends Synchr[boolean](this) { case class C() extends SyncVar[boolean] };
- object res1 extends Asynchr(this) { case class C(b: boolean); }
- object res2 extends Asynchr(this) { case class C(b: boolean); }
- object res1False extends Synchr[boolean](this) { case class C() extends SyncVar[boolean] };
- object res2False extends Synchr[boolean](this) { case class C() extends SyncVar[boolean] };
-
- rules(
- Pair(List(res, res1), { case List(r @ res.C(), res1.C(b)) =>
- if (b) r.set(b) else r.set(res1False(res1False.C())) }),
-
- Pair(List(res, res2), { case List(r @ res.C(), res2.C(b)) =>
- if (b) r.set(b) else r.set(res2False(res2False.C())) }),
-
- Pair(List(res1False, res2), { case List(r @ res1False.C(), res2.C(b)) =>
- r.set(b) }),
-
- Pair(List(res2False, res1), { case List(r @ res2False.C(), res1.C(b)) =>
- r.set(b) })
- );
-
- def apply(b1: => boolean, b2: => boolean): boolean = {
- concurrent.ops.spawn(res1(res1.C(b1)));
- concurrent.ops.spawn(res2(res2.C(b2)));
- res(res.C())
- }
-}
-*/
-object parallelOr {
-
- def main(args: Array[String]): unit = {
- def loop: boolean = { while (true) {}; true };
-/*
- System.out.println("true || true = " + or(true, true));
- System.out.println("false || false = " + or(false, false));
- System.out.println("false || true = " + or(false, true));
- System.out.println("true || false = " + or(true, false));
- System.out.println("true || loop = " + or(true, loop));
- System.out.println("loop || true = " + or(loop, true));
-*/
- }
-
-}
View
187 docs/examples/maps.scala
@@ -1,187 +0,0 @@
-package examples
-
-object maps {
-
- import scala.collection.immutable._
-
- trait MapStruct[kt, 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
- }
-
- class AlgBinTree[kt >: Null <: Ordered[kt], vt >: Null <: AnyRef]() extends MapStruct[kt, vt] {
- type map = AlgMap
-
- val empty: AlgMap = Empty()
-
- 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 {
- case Empty() => null
- case Node(k, v, l, r) =>
- if (key < k) l.apply(key)
- else if (key > k) r.apply(key)
- else v
- }
-
- def extend(key: kt, value: vt): map = this match {
- case Empty()=> Node(key, value, empty, empty)
- case Node(k, v, l, r) =>
- if (key < k) Node(k, v, l.extend(key, value), r)
- else if (key > k) Node(k, v, l, r.extend(key, value))
- else Node(k, value, l, r)
- }
-
- def remove(key: kt): map = this match {
- case Empty()=> empty
- case Node(k, v, l, r) =>
- if (key < k) Node(k, v, l.remove(key), r)
- else if (key > k) Node(k, v, l, r.remove(key))
- else if (l == empty) r
- else if (r == empty) l
- else {
- val midKey = r.domain.head
- Node(midKey, r.apply(midKey), l, r.remove(midKey))
- }
- }
-
- def domain: Stream[kt] = this match {
- case Empty()=> Stream.empty
- case Node(k, v, l, r) => l.domain append Stream.cons(k, r.domain)
- }
-
- def range: Stream[vt] = this match {
- case Empty()=> Stream.empty
- case Node(k, v, l, r) => l.range append Stream.cons(v, r.range)
- }
- }
- }
-
- class OOBinTree[kt >: Null <: Ordered[kt], vt >: Null <: AnyRef]() extends MapStruct[kt, vt] {
- 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]
- }
- 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
- }
- 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;
- 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)
- 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))
- }
- 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 >: Null <: Ordered[kt], vt >: Null <: AnyRef]() extends MapStruct[kt, vt] {
- type map = MutMap
- class MutMap(key: kt, value: vt) extends Map {
- 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
-
- 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
- this
- }
-
- def remove(key: kt): map =
- if (this == empty) this
- else if (key < k) { l = l.remove(key); this }
- else if (key > k) { r = r.remove(key); this }
- else if (l == empty) r
- else if (r == empty) l
- else {
- var mid = r
- while (!(mid.l == empty)) { mid = mid.l }
- mid.r = r.remove(mid.k)
- mid.l = l
- mid
- }
-
- def domain: Stream[kt] =
- if (this == empty) Stream.empty
- 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)
- }
- val empty = new MutMap(null, null)
- }
-
- class Date(y: Int, m: Int, d: Int) extends Ordered[Date] {
- def year = y
- def month = m
- def day = d
-
- def compare(other: Date): Int =
- if (year == other.year &&
- month == other.month &&
- day == other.day)
- 0
- else if (year < other.year ||
- year == other.year && month < other.month ||
- month == other.month && day < other.day)
- -1
- else
- 1
-
- override def equals(that: Any): Boolean =
- that.isInstanceOf[Date] && {
- val o = that.asInstanceOf[Date];
- day == o.day && month == o.month && year == o.year
- }
- }
-
- def main(args: Array[String]) {
- val t = new OOBinTree[Date, String]()
- ()
- }
-
-}
-
-
-
View
86 docs/examples/monads/callccInterpreter.scala
@@ -1,86 +0,0 @@
-object callccInterpreter {
-
- def id[a](x: a) = x
-
- type Answer = Value;
-
- case class M[A](in: (A => Answer) => Answer) {
- def bind[B](k: A => M[B]) = M[B](c => in (a => k(a) in c));
- def map[B](f: A => B): M[B] = bind(x => unitM(f(x)));
- def flatMap[B](f: A => M[B]): M[B] = bind(f);
- }
-
- def unitM[A](a: A) = M[A](c => c(a));
-
- def showM(m: M[Value]): String = (m in id).toString();
-
- def callCC[A](h: (A => M[A]) => M[A]) =
- M[A](c => h(a => M[A](d => c(a))) in c);
-
- type Name = String;
-
- trait Term;
- case class Var(x: Name) extends Term;
- case class Con(n: Int) extends Term;
- case class Add(l: Term, r: Term) extends Term;
- case class Lam(x: Name, body: Term) extends Term;
- case class App(fun: Term, arg: Term) extends Term;
- case class Ccc(x: Name, t: Term) extends Term;
-
- trait Value;
- case object Wrong extends Value {
- override def toString() = "wrong"
- }
- case class Num(n: Int) extends Value {
- override def toString() = n.toString();
- }
- case class Fun(f: Value => M[Value]) extends Value {
- override def toString() = "<function>"
- }
-
- type Environment = List[Pair[Name, Value]];
-
- def lookup(x: Name, e: Environment): M[Value] = e match {
- case List() => unitM(Wrong)
- case Pair(y, b) :: e1 => if (x == y) unitM(b) else lookup(x, e1)
- }
-
- def add(a: Value, b: Value): M[Value] = Pair(a, b) match {
- case Pair(Num(m), Num(n)) => unitM(Num(m + n))
- case _ => unitM(Wrong)
- }
-
- def apply(a: Value, b: Value): M[Value] = a match {
- case Fun(k) => k(b)
- case _ => unitM(Wrong)
- }
-
- def interp(t: Term, e: Environment): M[Value] = t match {
- case Var(x) => lookup(x, e)
- case Con(n) => unitM(Num(n))
- case Add(l, r) => for (a <- interp(l, e);
- b <- interp(r, e);
- c <- add(a, b))
- yield c
- case Lam(x, t) => unitM(Fun(a => interp(t, Pair(x, a) :: e)))
- case App(f, t) => for (a <- interp(f, e);
- b <- interp(t, e);
- c <- apply(a, b))
- yield c
- case Ccc(x, t) => callCC(k => interp(t, Pair(x, Fun(k)) :: e))
- }
-
- def test(t: Term): String =
- showM(interp(t, List()));
-
- val term0 = App(Lam("x", Add(Var("x"), Var("x"))), Add(Con(10), Con(11)));
- val term1 = App(Con(1), Con(2));
- val term2 = Add(Con(1), Ccc("k", Add(Con(2), App(Var("k"), Con(4)))));
-
- def main(args: Array[String]) = {
- System.out.println(test(term0));
- System.out.println(test(term1));
- System.out.println(test(term2));
- }
-}
-
View
55 docs/examples/monads/directInterpreter.scala
@@ -1,55 +0,0 @@
-object directInterpreter {
-
- type Name = String;
-
- trait Term;
- case class Var(x: Name) extends Term;
- case class Con(n: Int) extends Term;
- case class Add(l: Term, r: Term) extends Term;
- case class Lam(x: Name, body: Term) extends Term;
- case class App(fun: Term, arg: Term) extends Term;
-
- trait Value;
- case object Wrong extends Value;
- case class Num(n: Int) extends Value;
- case class Fun(f: Value => Value)extends Value;
-
- def showval(v: Value): String = v match {
- case Wrong => "<wrong>"
- case Num(n) => n.toString()
- case Fun(f) => "<function>"
- }
-
- type Environment = List[Pair[Name, Value]];
-
- def lookup(x: Name, e: Environment): Value = e match {
- case List() => Wrong
- case Pair(y, b) :: e1 => if (x == y) b else lookup(x, e1)
- }
-
- def add(a: Value, b: Value): Value = Pair(a, b) match {
- case Pair(Num(m), Num(n)) => Num(m + n)
- case _ => Wrong
- }
-
- def apply(a: Value, b: Value) = a match {
- case Fun(k) => k(b)
- case _ => Wrong
- }
-
- def interp(t: Term, e: Environment): Value = t match {
- case Var(x) => lookup(x, e)
- case Con(n) => Num(n)
- case Add(l, r) => add(interp(l, e), interp(r, e))
- case Lam(x, t) => Fun(a => interp(t, Pair(x, a) :: e))
- case App(f, t) => apply(interp(f, e), interp(t, e))
- }
-
- def test(t: Term): String =
- showval(interp(t, List()));
-
- val term0 = App(Lam("x", Add(Var("x"), Var("x"))), Add(Con(10), Con(11)));
-
- def main(args: Array[String]) =
- System.out.println(test(term0));
-}
View
86 docs/examples/monads/errorInterpreter.scala
@@ -1,86 +0,0 @@
-object errorInterpreter {
-
- trait M[A] {
- def show: String
- def bind[B](k: A => M[B]): M[B]
- def map[B](f: A => B): M[B] = bind(x => unitM(f(x)))
- def flatMap[B](f: A => M[B]): M[B] = bind(f)
- }
-
- def unitM[A](a: A): M[A] = new Suc(a)
- def errorM[A](msg: String): M[A] = new Err(msg)
-
- def showM(m: M[Value]): String = m.show
-
- class Suc[A](x: A) extends M[A] {
- def bind[B](k: A => M[B]): M[B] = k(x)
- def show: String = "Success: " + x
- }
- class Err[A](msg: String) extends M[A] {
- def bind[B](k: A => M[B]): M[B] = new Err(msg)
- def show: String = "Error: " + msg
- }
-
- type Name = String
-
- trait Term
- case class Var(x: Name) extends Term
- case class Con(n: Int) extends Term
- case class Add(l: Term, r: Term) extends Term
- case class Lam(x: Name, body: Term) extends Term
- case class App(fun: Term, arg: Term) extends Term
-
- trait Value
- case object Wrong extends Value {
- override def toString() = "wrong"
- }
- case class Num(n: Int) extends Value {
- override def toString() = n.toString()
- }
- case class Fun(f: Value => M[Value]) extends Value {
- override def toString() = "<function>"
- }
-
- type Environment = List[Pair[Name, Value]]
-
- def lookup(x: Name, e: Environment): M[Value] = e match {
- case List() => errorM("unbound variable: " + x);
- case Pair(y, b) :: e1 => if (x == y) unitM(b) else lookup(x, e1)
- }
-
- def add(a: Value, b: Value): M[Value] = Pair(a, b) match {
- case Pair(Num(m), Num(n)) => unitM(Num(m + n))
- case _ => errorM("should be numbers: " + a + "," + b)
- }
-
- def apply(a: Value, b: Value): M[Value] = a match {
- case Fun(k) => k(b)
- case _ => errorM("should be function: " + a)
- }
-
- def interp(t: Term, e: Environment): M[Value] = t match {
- case Var(x) => lookup(x, e)
- case Con(n) => unitM(Num(n))
- case Add(l, r) => for (a <- interp(l, e);
- b <- interp(r, e);
- c <- add(a, b))
- yield c
- case Lam(x, t) => unitM(Fun(a => interp(t, Pair(x, a) :: e)))
- case App(f, t) => for (a <- interp(f, e);
- b <- interp(t, e);
- c <- apply(a, b))
- yield c
- }
-
- def test(t: Term): String =
- showM(interp(t, List()))
-
- val term0 = App(Lam("x", Add(Var("x"), Var("x"))), Add(Con(10), Con(11)))
- val term1 = App(Con(1), Con(2))
-
- def main(args: Array[String]) = {
- System.out.println(test(term0))
- System.out.println(test(term1))
- }
-}
-
View
75 docs/examples/monads/simpleInterpreter.scala
@@ -1,75 +0,0 @@
-object simpleInterpreter {
-
- case class M[A](value: A) {
- def bind[B](k: A => M[B]): M[B] = k(value);
- def map[B](f: A => B): M[B] = bind(x => unitM(f(x)));
- def flatMap[B](f: A => M[B]): M[B] = bind(f);
- }
-
- def unitM[A](a: A): M[A] = M(a);
-
- def showM(m: M[Value]): String = m.value.toString();
-
- type Name = String;
-
- trait Term;
- case class Var(x: Name) extends Term;
- case class Con(n: Int) extends Term;
- case class Add(l: Term, r: Term) extends Term;
- case class Lam(x: Name, body: Term) extends Term;
- case class App(fun: Term, arg: Term) extends Term;
-
- trait Value;
- case object Wrong extends Value {
- override def toString() = "wrong"
- }
- case class Num(n: Int) extends Value {
- override def toString() = n.toString();
- }
- case class Fun(f: Value => M[Value]) extends Value {
- override def toString() = "<function>"
- }
-
- type Environment = List[Pair[Name, Value]];
-
- def lookup(x: Name, e: Environment): M[Value] = e match {
- case List() => unitM(Wrong)
- case Pair(y, b) :: e1 => if (x == y) unitM(b) else lookup(x, e1)
- }
-
- def add(a: Value, b: Value): M[Value] = Pair(a, b) match {
- case Pair(Num(m), Num(n)) => unitM(Num(m + n))
- case _ => unitM(Wrong)
- }
-
- def apply(a: Value, b: Value): M[Value] = a match {
- case Fun(k) => k(b)
- case _ => unitM(Wrong)
- }
-
- def interp(t: Term, e: Environment): M[Value] = t match {
- case Var(x) => lookup(x, e)
- case Con(n) => unitM(Num(n))
- case Add(l, r) => for (a <- interp(l, e);
- b <- interp(r, e);
- c <- add(a, b))
- yield c
- case Lam(x, t) => unitM(Fun(a => interp(t, Pair(x, a) :: e)))
- case App(f, t) => for (a <- interp(f, e);
- b <- interp(t, e);
- c <- apply(a, b))
- yield c
- }
-
- def test(t: Term): String =
- showM(interp(t, List()));
-
- val term0 = App(Lam("x", Add(Var("x"), Var("x"))), Add(Con(10), Con(11)));
- val term1 = App(Con(1), Con(2));
-
- def main(args: Array[String]) = {
- System.out.println(test(term0));
- System.out.println(test(term1));
- }
-}
-
View
86 docs/examples/monads/stateInterpreter.scala
@@ -1,86 +0,0 @@
-package examples.monads;
-
-object stateInterpreter {
-
- type State = Int;
-
- val tickS = new M(s => Pair((), s + 1));
-
- case class M[A](in: State => Pair[A, State]) {
- def bind[B](k: A => M[B]) = M[B]{ s0 =>
- val Pair(a, s1) = this in s0; k(a) in s1
- }
- def map[B](f: A => B): M[B] = bind(x => unitM(f(x)));
- def flatMap[B](f: A => M[B]): M[B] = bind(f);
- }
-
- def unitM[A](a: A) = M[A](s => Pair(a, s));
-
- def showM(m: M[Value]): String = {
- val Pair(a, s1) = m in 0;
- "Value: " + a + "; Count: " + s1
- }
-
- type Name = String;
-
- trait Term;
- case class Var(x: Name) extends Term;
- case class Con(n: Int) extends Term;
- case class Add(l: Term, r: Term) extends Term;
- case class Lam(x: Name, body: Term) extends Term;
- case class App(fun: Term, arg: Term) extends Term;
-
- trait Value;
- case object Wrong extends Value {
- override def toString() = "wrong"
- }
- case class Num(n: Int) extends Value {
- override def toString() = n.toString();
- }
- case class Fun(f: Value => M[Value]) extends Value {
- override def toString() = "<function>"
- }
-
- type Environment = List[Pair[Name, Value]];
-
- def lookup(x: Name, e: Environment): M[Value] = e match {
- case List() => unitM(Wrong)
- case Pair(y, b) :: e1 => if (x == y) unitM(b) else lookup(x, e1)
- }
-
- def add(a: Value, b: Value): M[Value] = Pair(a, b) match {
- case Pair(Num(m), Num(n)) => for (_ <- tickS) yield Num(m + n)
- case _ => unitM(Wrong)
- }
-
- def apply(a: Value, b: Value): M[Value] = a match {
- case Fun(k) => for (_ <- tickS; c <- k(b)) yield c
- case _ => unitM(Wrong)
- }
-
- def interp(t: Term, e: Environment): M[Value] = t match {
- case Var(x) => lookup(x, e)
- case Con(n) => unitM(Num(n))
- case Add(l, r) => for (a <- interp(l, e);
- b <- interp(r, e);
- c <- add(a, b))
- yield c
- case Lam(x, t) => unitM(Fun(a => interp(t, Pair(x, a) :: e)))
- case App(f, t) => for (a <- interp(f, e);
- b <- interp(t, e);
- c <- apply(a, b))
- yield c
- }
-
- def test(t: Term): String =
- showM(interp(t, List()));
-
- val term0 = App(Lam("x", Add(Var("x"), Var("x"))), Add(Con(10), Con(11)));
- val term1 = App(Con(1), Con(2));
-
- def main(args: Array[String]) = {
- System.out.println(test(term0));
- System.out.println(test(term1));
- }
-}
-
View
64 docs/examples/oneplacebuffer.scala
@@ -1,64 +0,0 @@
-package examples
-
-object oneplacebuffer {
-
- import scala.actors.Actor._
- import scala.concurrent.ops
-
- class OnePlaceBuffer {
- private case class Put(x: Int)
- private case object Get
-
- private val m = actor {
- var buf: Option[Int] = None
- loop {
- react {
- case Put(x) if buf.isEmpty =>
- println("put "+x);
- buf = Some(x); reply()
- case Get if !buf.isEmpty =>
- val x = buf.get
- println("get "+x)
- buf = None; reply(x)
- }
- }
- }
- m.start()
-
- def write(x: Int) { m !? Put(x) }
-
- def read(): Int = (m !? Get).asInstanceOf[Int]
- }
-
- def kill(delay: Int) = new java.util.Timer().schedule(
- new java.util.TimerTask {
- override def run() {
- println("[killed]")
- sys exit 0
- }
- },
- delay) // in milliseconds
-
- def main(args: Array[String]) {
- val buf = new OnePlaceBuffer
- val random = new java.util.Random()
-
- def producer(n: Int) {
- Thread.sleep(random nextInt 1000)
- buf write n
- producer(n + 1)
- }
-
- def consumer {
- Thread.sleep(random nextInt 1000)
- val n = buf.read()
- consumer
- }
-
- ops spawn producer(0)
- ops spawn consumer
- kill(10000)
- }
-
-}
-
View
57 docs/examples/parsing/ArithmeticParser.scala
@@ -1,57 +0,0 @@
-/* __ *\
-** ________ ___ / / ___ Scala API **
-** / __/ __// _ | / / / _ | (c) 2006-2011, LAMP/EPFL **
-** __\ \/ /__/ __ |/ /__/ __ | **
-** /____/\___/_/ |_/____/_/ | | **
-** |/ **
-\* */
-
-package examples.parsing
-
-import scala.util.parsing.combinator.lexical.StdLexical
-import scala.util.parsing.combinator.syntactical.StdTokenParsers
-
-/** Parse and evaluate a numeric expression as a sequence of terms, separated by + or -
- * a term is a sequence of factors, separated by * or /
- * a factor is a parenthesized expression or a number
- *
- * @author Adriaan Moors
- */
-object arithmeticParser extends StdTokenParsers {
- type Tokens = StdLexical ; val lexical = new StdLexical
- lexical.delimiters ++= List("(", ")", "+", "-", "*", "/")
-
- lazy val expr = term*("+" ^^^ {(x: int, y: int) => x + y} | "-" ^^^ {(x: int, y: int) => x - y})
- lazy val term = factor*("*" ^^^ {(x: int, y: int) => x * y} | "/" ^^^ {(x: int, y: int) => x / y})
- lazy val factor: Parser[int] = "(" ~> expr <~ ")" | numericLit ^^ (_.toInt)
-
- def main(args: Array[String]) {
- println(
- if (args.length == 1) {
- expr(new lexical.Scanner(args(0)))
- }
- else
- "usage: scala examples.parsing.arithmeticParser <expr-string>"
- )
- }
-}
-
-
-object arithmeticParserDesugared extends StdTokenParsers {
- type Tokens = StdLexical ; val lexical = new StdLexical
- lexical.delimiters ++= List("(", ")", "+", "-", "*", "/")
-
- lazy val expr = chainl1(term, (keyword("+").^^^{(x: int, y: int) => x + y}).|(keyword("-").^^^{(x: int, y: int) => x - y}))
- lazy val t