Last active
September 28, 2016 06:50
-
-
Save diggzhang/10885916d0e4ee1dbf41810c079ca2b4 to your computer and use it in GitHub Desktop.
实验楼scala公开课temp code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object FileMatcher { | |
private def fileHere = (new java.ui.File(".")).listFiles | |
def filesMatching( | |
matcher: (String) => Boolean) = { | |
for(file <- filesHere; if matcher(file.getName)) | |
yield file | |
} | |
def filesEnding(query: String) = | |
filesMatching(_.endsWith(query)) | |
def filesContaining(query: String) = | |
filesMatching(_.contains(query)) | |
def filesRegex(qurey: String) = | |
filesMatching(_.matches(query)) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.io.Source | |
object LongLines { | |
def processFile(filename: String, width: Int) = { | |
val source = Source.fromFile(filename) | |
for (line <- source.getLines()) | |
processLine(filename, width, line) | |
} | |
private def processLine(filename: String, width: Int, line: String) { | |
if (line.length > width) { | |
println(filename + " : " + line.trim) | |
} | |
} | |
} | |
object LongLines { | |
def processFile(filename: String, width: Int) { | |
def processLine(line: String) = { | |
if(line.length > width) | |
println(filename + " : " + line.trim) | |
} | |
} | |
val source = Source.fromFile(filename) | |
for { | |
line <- source.getLines() | |
} processLine(line) | |
} | |
LongLines.processFile(args(0), args(1).toInt) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import scala.collection.mutable.Map | |
class ChecksumAccumulator{ | |
private var sum=0 | |
def add(b:Byte) :Unit = sum +=b | |
def checksum() : Int = ~ (sum & 0xFF) +1 | |
} | |
object ChecksumAccumulator { | |
private val cache = Map [String, Int] () | |
def calculate(s:String) : Int = | |
if(cache.contains(s)) | |
cache(s) | |
else { | |
val acc=new ChecksumAccumulator | |
for( c <- s) | |
acc.add(c.toByte) | |
val cs=acc.checksum() | |
cache += ( s -> cs) | |
cs | |
} | |
} | |
println ( ChecksumAccumulator.calculate("Welcome to Scala Chinese community")) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object Element { | |
private class ArrayElement(val contents: Array[String]) | |
extends Element | |
private class LineElement(s:String) extends Element { | |
val contents=Array(s) | |
override def width = s.length | |
override def height = 1 | |
} | |
private class UniformElement (ch :Char, | |
override val width:Int, | |
override val height:Int | |
) extends Element{ | |
private val line=ch.toString * width | |
def contents = Array.fill(height)(line) | |
} | |
def elem(contents: Array[String]):Element = | |
new ArrayElement(contents) | |
def elem(chr:Char, width:Int, height:Int) :Element = | |
new UniformElement(chr,width,height) | |
def elem(line:String) :Element = | |
new LineElement(line) | |
} | |
import Element.elem | |
abstract class Element { | |
def contents: Array[String] | |
def height: Int = contents.length | |
def width: Int = contents(0).length | |
def above(that: Element) :Element = { | |
val this1=this widen that.width | |
val that1=that widen this.width | |
elem (this1.contents ++ that1.contents) | |
} | |
def beside(that: Element) :Element = { | |
val this1=this heighten that.height | |
val that1=that heighten this.height | |
Element.elem( | |
for( | |
(line1,line2) <- this1.contents zip that1.contents | |
) yield line1+line2 | |
) | |
} | |
def widen(w: Int): Element = | |
if (w <= width) this | |
else { | |
val left = Element.elem(' ', (w - width) / 2, height) | |
var right = Element.elem(' ', w - width - left.width, height) | |
left beside this beside right | |
} | |
def heighten(h: Int): Element = | |
if (h <= height) this | |
else { | |
val top = Element.elem(' ', width, (h - height) / 2) | |
var bot = Element.elem(' ', width, h - height - top.height) | |
top above this above bot | |
} | |
override def toString = contents mkString "\n" | |
} | |
object Spiral { | |
val space = elem (" ") | |
val corner = elem ("+") | |
def spiral(nEdges:Int, direction:Int): Element = { | |
if(nEdges==1) | |
elem("+") | |
else{ | |
val sp=spiral(nEdges -1, (direction +3) % 4) | |
def verticalBar = elem ('|',1, sp.height) | |
def horizontalBar = elem('-',sp.width,1) | |
if(direction==0) | |
(corner beside horizontalBar) above (sp beside space) | |
else if (direction ==1) | |
(sp above space) beside ( corner above verticalBar) | |
else if(direction ==2 ) | |
(space beside sp) above (horizontalBar beside corner) | |
else | |
(verticalBar above corner) beside (space above sp) | |
} | |
} | |
def main(args:Array[String]) { | |
val nSides=args(0).toInt | |
println(spiral(nSides,0)) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
val hereVar = 42.toString | |
println(hereVar) | |
if (scala == null) {} | |
42 max 43 | |
val x = "hellowo".substring(2) | |
import java.lang._ | |
import scala._ | |
import Predef._ | |
import java.util.regex | |
import java.sql.{Date => SDate} | |
import com.sun.xml.internal.bind.v2.model.nav.Navigator | |
SDate.valueOf() | |
class AStarB { | |
val pat = regex.Pattern.compile("a*b") | |
} | |
-98.abs | |
class Outer { | |
class Innter { | |
private def f() { println("f") } | |
class InnterMost { | |
f() | |
} | |
} | |
(new Innter).f() | |
} | |
val what = new Outer | |
package p { | |
} | |
package bobsrockets { | |
package navigation { | |
private[bobsrockets] class Navigator { | |
protected[navigation] def useStarChart() {} | |
class LegOfJourney { | |
private[Navigator] val distance = 100 | |
} | |
// object-private | |
private[this] var speed = 200 | |
} | |
} | |
package launch { | |
import navigation._ | |
object Vehicle { | |
private[launch] val guide = new Navigator | |
} | |
} | |
} | |
// 这里私有保护类访问 | |
// 是伴生类的私有成员 | |
class Rocket { | |
import Rocket.fuel | |
private def canGoHomeAgain = fuel > 20 | |
} | |
object Rocket { | |
private def fuel = 10 | |
def chooseStrategy(rocket: Rocket): Unit = { | |
if (rocket.canGoHomeAgain) | |
goHome() | |
else | |
pickAStar() | |
} | |
def goHome() {} | |
def pickAStar() {} | |
} | |
import akka.actor.FSM.Failure | |
import akka.actor.Status.Success | |
import scala.concurrent.ExecutionContext.Implicits.global | |
import scala.scala.util.Success | |
import scala.concurrent.Future | |
import scala.util.Random | |
type CoffeeBeans = String | |
type GroundCoffee = String | |
case class Water(temperature: Int) | |
type Milk = String | |
type FrothedMilk = String | |
type Espresso = String | |
type Cappuccino = String | |
def grind(beans: CoffeeBeans): Future[GroundCoffee] = Future { | |
println("start grinding...") | |
Thread.sleep(Random.nextInt(2000)) | |
if (beans == "baked beans") throw GrindingException("are you joking?") | |
println("finished grinding...") | |
s"ground coffee of $beans" | |
} | |
def heatWater(water: Water): Future[Water] = Future { | |
println("heating the water now") | |
Thread.sleep(Random.nextInt(2000)) | |
println("hot, it's hot!") | |
water.copy(temperature = 85) | |
} | |
def frothMilk(milk: Milk): Future[FrothedMilk] = Future { | |
println("milk frothing system engaged!") | |
Thread.sleep(Random.nextInt(2000)) | |
println("shutting down milk frothing system") | |
s"frothed $milk" | |
} | |
def brew(coffee: GroundCoffee, heatedWater: Water): Future[Espresso] = Future { | |
println("happy brewing :)") | |
Thread.sleep(Random.nextInt(2000)) | |
println("it's ggbrewed!") | |
"espresso" | |
} | |
grind("NetEaseCoffee").onComplete{ | |
case Success(ground) => println(s"got my $ground") | |
case Failure(ex) => println("This grinder needs a replacement") | |
} | |
val tempreatureOkey: Future[Boolean] = headWater(Water(25)) map { | |
water => { | |
(80 to 85) contains (water.temperature) | |
} | |
} | |
import scala.util.Try | |
// Some type aliases, just for getting more meaningful method signatures: | |
type CoffeeBeans = String | |
type GroundCoffee = String | |
case class Water(temperature: Int) | |
type Milk = String | |
type FrothedMilk = String | |
type Espresso = String | |
type Cappuccino = String | |
// dummy implementations of the individual steps: | |
def grind(beans: CoffeeBeans): GroundCoffee = s"ground coffee of $beans" | |
def heatWater(water: Water): Water ` water.copy(temperature ` 85) | |
def frothMilk(milk: Milk): FrothedMilk = s"frothed $milk" | |
def brew(coffee: GroundCoffee, heatedWater: Water): Espresso = "espresso" | |
def combine(espresso: Espresso, frothedMilk: FrothedMilk): Cappuccino = "cappuccino" | |
// some exceptions for things that might go wrong in the individual steps | |
// (we'll need some of them later, use the others when experimenting with the code): | |
case class GrindingException(msg: String) extends Exception(msg) | |
case class FrothingException(msg: String) extends Exception(msg) | |
case class WaterBoilingException(msg: String) extends Exception(msg) | |
case class BrewingException(msg: String) extends Exception(msg) | |
// going through these steps sequentially: | |
def prepareCappuccino(): Try[Cappuccino] = for { | |
ground <- Try(grind("arabica beans")) | |
water <- Try(heatWater(Water(25))) | |
espresso <- Try(brew(ground, water)) | |
foam <- Try(frothMilk("milk")) | |
} yield combine(espresso, foam) | |
var capital = Map("us" -> "new york", "cn" -> "beijing") | |
capital += ("jp" -> "tokyo") | |
println(capital) | |
for (city <- capital) println(city._1 + city._2) | |
class Rational(n: Int, d: Int) extends Ordered[Rational] { | |
def compare(that: Rational) = | |
(this.numer * that.denon) - (that.numer * this.denom) | |
} | |
trait Philosophical { | |
def philosophize(): Unit = { | |
println("I consume memeory, therefore I am !") | |
} | |
} | |
class Frog extends Philosophical { | |
override def toString = "green" | |
} | |
val frog = new Frog | |
frog.philosophize() | |
val phil: Philosophical = frog | |
phil.philosophize() | |
object Element { | |
def elem(contents: Array[String]): Element = | |
new ArrayElement(contents) | |
def elem(chr: Char, width: Int, height: Int): Element = | |
new UniformElement(chr, width, height) | |
def elem(line: String): Element = | |
new LineElement(line) | |
} | |
def beside(that: Element): Element = { | |
val contents = new Array[String](this.contents.length) | |
for (i <- 0 until this.contents.length) | |
} | |
class LineElement(s: String) extends Element { | |
val contents = Array(s) | |
override def width = s.length | |
override def height = 1 | |
} | |
class UniformElement | |
class ArrayElement(conts: Array[String]) extends Element { | |
def contents: Array[String] = conts | |
} | |
class Cat { | |
val dangerous = false | |
} | |
class Tiger( | |
override val dangerous: Boolean, | |
private var age: Int | |
) extends Cat | |
class Tiger(param1: Boolean, param2: Int) extends Cat { | |
override val dangerous = param1 | |
private var age = param2 | |
} | |
class LineElement(s: String) extends ArrayElement(Array(s)) { | |
override def width = s.length | |
override def height = 1 | |
} | |
abstract class Element { | |
def demo(): Unit = { | |
print("element's implementation invoked") | |
} | |
} | |
class ArrayElement extends Element { | |
override def demo(): Unit = { | |
println("array element implemention invoked") | |
} | |
} | |
class LineElement extends ArrayElement { | |
override def demo(): Unit = { | |
println("line element's invoked") | |
} | |
} | |
trait Doubling extends IntQueue { | |
abstract override def put(x: Int): Unit = { | |
super.put(2 * x) | |
} | |
} | |
val queue = new BasicIntQueue | |
import java.io.{File, PrintWriter} | |
import java.util.Date | |
abstract class Element { | |
def contents: Array[String] | |
def height: Int = contents.length | |
def width: Int = if (height == 0) 0 else contents(0).length | |
} | |
abstract class Element { | |
def contents: Array[String] | |
val height = contents.length | |
val width = | |
if (height == 0) 0 else contents(0).length | |
} | |
Array(1, 2, 3).toString | |
"abc".length | |
val ae = new ArrayEle | |
def plainOldSum(x: Int, y: Int) = x + y | |
plainOldSum(1,2) | |
def currySum(x: Int)(y: Int) = x + y | |
currySum(1)(2) | |
def first(x: Int) = (y: Int) => x + y | |
val second = first(1) | |
second(9) | |
def twice(op: Double => Double, x: Double) = op(op(x)) | |
twice(_ + 1, 5) | |
def withPrintWriter(file: File, op: PrintWriter => Unit): Unit = { | |
val writer = new PrintWriter(file) | |
try { | |
op(writer) | |
} finally { | |
writer.close() | |
} | |
} | |
def withPrintWriter(file: File)(op: PrintWriter => Unit): Unit = { | |
val writer = new PrintWriter(file) | |
try { | |
op(writer) | |
} finally { | |
writer.close() | |
} | |
} | |
val file = new File("date.txt") | |
withPrintWriter(file) { | |
writer => writer.println(new Date()) | |
} | |
import java.io.File | |
import scala.io.Source | |
object FileMatcher { | |
private def filesHere = (new File(".")).listFiles() | |
private def filesMatching(matcher: String => Boolean) = | |
for (file <- filesHere; if matcher(file.getName)) | |
yield file | |
def echo(args: String*) = | |
for (arg <- args) println(arg) | |
def filesEnding(query: String) = | |
filesMatching(_.endsWith(query)) | |
def filesContaining(query: String) = | |
filesMatching(_.contains(query)) | |
def filesRegex(query: String) = | |
filesMatching(_.matches(query)) | |
} | |
def containsNeg(nums: List[Int]): Boolean = { | |
var exists = false | |
for(num <- nums) | |
if (num < 0) | |
exists = true | |
exists | |
} | |
containsNeg(List(1,2,3,4)) | |
containsNeg(List()) | |
def containsNeg(name: List[Int]) = num.exists(_ < 0) | |
def containsOdd(nums: List[Int]): Boolean = { | |
var exists = false | |
for (num <- nums) | |
if (num % 2 == 1) | |
exists = true | |
exists | |
} | |
def echo(args: String*) = | |
for (arg <- args) println(arg) | |
echo() | |
echo("one") | |
echo("hello", "world") | |
val arr = Array("What's", "up", "doc?") | |
echo(arr) | |
echo(arr: _*) | |
def approximate(guess: Double): Double = | |
if (isGoodEnough(guess)) guess | |
else approximate(improve(guess)) | |
def approximateLoop(initialGuess: Double): Double = { | |
var guess = initialGuess | |
while (!isGoodEnough(guess)) | |
guess = improve(guess) | |
guess | |
} | |
object FileMatcher { | |
private def filesHere = (new java.io.File(".")).listFiles | |
def filesEnding(query: String) = | |
for (file <- filesHere; if file.getName.endsWith(query)) | |
yield file | |
} | |
def filesContaining(query: String) = | |
for (file <- fileHere; if file.getName.con) | |
object LongLines { | |
def processFile(filename: String, width: Int): Unit = { | |
val source = Source.fromFile(filename) | |
for (line <- source.getLines()) | |
processLine(filename, width, line) | |
} | |
private def processLine(filename: String, width: Int, line: String): Unit = { | |
if (line.length > width) | |
println(filename + " : " + line.trim) | |
} | |
} | |
val firstArg = if (!args.isEmpty) args(0) else "" | |
val friend = | |
firstArg match { | |
case "salt" => "pepper" | |
case "chips" => "salsa" | |
case "eggs" => "bacon" | |
case _ => "huh?" | |
} | |
println(friend) | |
def printMultiTable(): Unit = { | |
var i = 1 | |
while( i <= 10 ) { | |
var j = 1 | |
while ( j <= 10 ) { | |
val prod = (i * j).toString | |
var k = prod.length | |
while ( k < 4 ) { | |
print(" ") | |
k += 1 | |
} | |
print(prod) | |
j += 1 | |
} | |
println() | |
i += 1 | |
} | |
} | |
import java.net.URL | |
import java.net.MalformedURLException | |
def urlFor(path: String) = | |
try { | |
new URL(path) | |
} catch { | |
case e: MalformedURLException => | |
new URL("http://www.janda.net") | |
} | |
import java.io.FileReader | |
import java.io.FileNotFoundException | |
import java.io.IOException | |
try { | |
val f = new FileReader("input.txt") | |
} catch { | |
case ex: FileNotFoundException => ??? | |
case ex: IOException => ??? | |
} | |
import java.io.File | |
val filesHere = (new File(".")).listFiles() | |
for ( | |
file <- filesHere | |
if file.isFile | |
if file.getName.endsWith(".sh") | |
) println(file) | |
def fileLines(file: java.io.File) = | |
scala.io.Source.fromFile(file).getLines().toList | |
def grep(pattern: String) = | |
for { | |
file <- filesHere | |
if file.getName.endsWith(".sh") | |
line <- fileLines(file) | |
if line.trim.matches(pattern) | |
} println(file + " : " + line.trim) | |
grep(".*sh.*") | |
def scalaFiles = | |
for { | |
file <- filesHere | |
if file.getName.endsWith(".sh") | |
} yield file | |
for (file <- filesHere if file.getName.endsWith(".sh")) { | |
yield | |
} | |
val forLineLengths = | |
for { | |
file <- filesHere | |
if file.getName.endsWith(".sh") | |
line <- fileLines(file) | |
trimmed = line.trim | |
if trimmed.matches(".*.sh.*") | |
} yield trimmed.length | |
val half = | |
if (n % 2 == 0) | |
n / 2 | |
else | |
throw new RuntimeException("n must be even") | |
class Rational(n: Int, d: Int) { | |
require(d != 0) | |
override def toString = n + "/" + d | |
def add(that: Rational): Rational = | |
new Rational(n * that.d + that.n * d, d * that.d) | |
} | |
class Rational(n: Int, d: Int) { | |
require(d != 0) | |
val numer: Int = n | |
val demon: Int = d | |
override def toString = numer + "/" + demon | |
def add(that: Rational): Rational = | |
new Rational( | |
numer * that.demon + that.numer * demon, | |
demon * that.demon | |
) | |
def lessThan(that: Rational) = | |
this.numer * that.demon < that.numer * this.denom | |
def max(that: Rational) = | |
if (this.lessThan(that)) that else this | |
} | |
val oneHalf = new Rational(1, 2) | |
val twoThirds = new Rational(2, 3) | |
oneHalf add twoThirds | |
val y = new Rational(3) | |
new Rational(66, 42) | |
class Rational_gcd(n: Int, d: Int) { | |
require(d != 0) | |
private val g = gcd(n.abs, d.abs) | |
val numer = n / g | |
val denom = d / g | |
def this(n: Int) = this(n, 1) | |
def add(that: Rational): Rational = | |
new Rational( | |
numer * that.denom + that.numer * denom, | |
denom * that.denom | |
) | |
override def toString = numer+"/"+denom | |
private def gcd(a: Int, b: Int): Int = | |
if (b == 0) a else gcd(b, a % b) | |
} | |
new Rational_gcd(66, 42) | |
val xx = new Rational(1, 2) | |
val xy = new Rational(2, 3) | |
class Rational_reload(n: Int, d: Int) { | |
require(d != 0) | |
private val g = gcd(n.abs, d.abs) | |
val numer = n / g | |
val denon = d / g | |
def this(n: Int) = this(n, 1) | |
def +(that: Rational): Rational = | |
new Rational( | |
numer * that.denom + that.numer * denom, | |
denom * that.denom | |
) | |
def +(i: Int): Rational = | |
new Rational(numer + i * denom, denom) | |
def -(that: Rational): Rational = | |
new Rational( | |
numer * that.denom - that.numer * denom, | |
denom * that.denom | |
) | |
def -(i: Int): Rational = | |
new Rational(numer - i* denom, denom) | |
def *(that: Rational): Rational = | |
new Rational(numer * that.numer, denom * that.denom) | |
def *(i: Int): Rational = | |
new Rational(numer * i, denom) | |
def /(that: Rational): Rational = | |
new Rational(numer * that.denom, denom * that.numer) | |
def /(i: Int): Rational = | |
new Rational(numer, denom * i) | |
override def toString = numer+"/"+denom | |
private def gcd(a: Int, b: Int): Int = | |
if (b == 0) a else gcd(b, a % b) | |
} | |
def gcdLoop(x: Long, y: Long): Long = { | |
var a = x | |
var b = y | |
while ( a != 0) { | |
val temp = a | |
a = b % a | |
b = temp | |
} | |
b | |
} | |
val line = "" | |
do { | |
line = readLine() | |
println("Read: " + line) | |
} while (line != null) | |
val z = new Rational(5, 0) | |
import scala.collection.mutable.Map | |
import java.lang | |
import scala.Predef | |
object ChecksumAccumulator { | |
private val cache = Map[String, Int]() | |
def calculate(s: String): Int = | |
if (cache.contains(s)) | |
cache(s) | |
else { | |
val acc = new ChecksumAccumulator | |
for (c <- s) | |
acc.add(c.toByte) | |
val cs = acc.checksum() | |
cache += (s -> cs) | |
cs | |
} | |
} | |
class ChecksumAccumulator { | |
private var sum = 0 | |
def add(b: Byte) { sum += b } | |
def checksum(): Int = ~(sum & 0xFF) + 1 | |
} | |
//import ChecksumAccumulator.calculate | |
object Summer { | |
def main(args: Array[String]): Unit = { | |
for (arg <- args) | |
println(arg + " : " + calculate(arg)) | |
} | |
} | |
import ChecksumAccumulator.calculate | |
//app == main | |
object FallWinterSpringSummer extends App { | |
for (season <- List("fall", "winter", "spring")) | |
println(season + " + " + calculate(season)) | |
} | |
val acc = new ChecksumAccumulator | |
val csa = new ChecksumAccumulator | |
acc.add(1) | |
import scala.collection.mutable.Map | |
case class ChecksumAccumulator | |
object ChecksumAccumulator { | |
private val cache = Map[String, Int]() | |
def calculate(s: String): Int = { | |
if (cache.contains(s)) { | |
cache(s) | |
} else { | |
val acc = new ChecksumAccumulator | |
for (c <- s) | |
acc.add(c.toByte) | |
val cs = acc.checksum() | |
cache += (s -> cs) | |
cs | |
} | |
} | |
} | |
class ChecksumAccumllator { | |
var sum = 1992 | |
private var pInHere = "im private string" | |
def add(b: Byte): Unit = { | |
sum += b | |
} | |
def checksum(): Int = { | |
return ~(sum & 0xFF) + 1 | |
} | |
} | |
val acc = new ChecksumAccumllator | |
acc.sum = 1993 | |
acc.add(12) | |
acc.checksum() | |
val cca = new ChecksumAccumllator | |
cca.sum | |
def printargs(args: Array[String]): Unit = { | |
for(arg <- args) { | |
println(arg) | |
} | |
} | |
def formatArgs(args: Array[String]): String = args.mkString("\n") | |
//printargs(Array("a","b")) | |
val res11 = formatArgs(Array("a", "b", "b")) | |
assert(res11 == "a\nb\nb") | |
val s = "Hello" | |
println(s) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment