def myFun(x:Integer) = "Look, " + x + " * " + x + " = " + (x * x)
val sameThing = (x: Integer) => "Look, " + x + " * " + x + " = " + (x * x)
List(1,2,3) map {x => x * x * x}
List(0., 3.14159265358) map { sin(_) }
def const[X, Y](y: Y) = (x: X) => y
def c123 = const(123)
val x = c123("abc") // it is 123
, .
Scala , :
val list = "Clatto" :: "Verata" :: "Nicto" :: Nil // Same as List("Clatto", "Verata", "Nicto")
val list = List("double", "double") ::: List("toil", "and", "trouble") // concatenation
list.exists(x => x.toString.length == 4) // wtf method of looking for TRUE
list.drop(2).dropRight(4).filter(s => (s endsWith "y"))
list.map(s => "\"" + s + "\"") // list comprehension
List(1,2).flatMap(List(123,_,456)) // lists built by List(123,_,456) are concatenated
list.foreach(print)
list.reverse
list.head
list.tail
list.last
, , :
val list = List(1,2,3,4,5)
// folds the list, adding up the elements:
list.foldLeft(0)(_+_)
val second : List[Int] => Int = {
case x::y::_ => y
}
:
val second = new PartialFunction[List[Int], Int] {
def apply(xs: List[Int]) = xs match {
case x :: y :: _ => y
}
def isDefinedAt(xs: List[Int]) = xs match {
case x :: y :: _ => truecase _ => false
}
( x::y::z::NilList(x, y, z)).
-:
val pf : PartialFunction[X,Y] = ...
val y = pf(x) // exception happens if pf is not defined on the value of x
val yOpt : Option[Y] = pf.lift(x) // returns either Some(y) or None
val b : Boolean = pf.isDefinedAt(x)
val pfAlt : PartialFunction[X,Y] = ...
val y = pf.orElse(pf1) // if (pf.isDefinedAt(x)) pf(x) else pf1(x)
, : , -; - , ? , ,
class A(i:Integer) {
def f1(j: Integer, k: Integer) = i+j+k
val f2 = (j:Integer, k: Integer) => i+j+k
}
val orders = List[Order](
// use premium pricing strategynew Order to buy(100 sharesOf "IBM")
maxUnitPrice 300
using premiumPricing,
// use default pricing strategynew Order to buy(200 sharesOf "GOOGLE")
maxUnitPrice 300
using defaultPricing,
// use custom pricing strategynew Order to sell(200 bondsOf "Sun")
maxUnitPrice 300
using {
(qty, unit) => qty * unit - 500
}
, - Scala, . , .
:
Scala - . Java - .
. , )switch/case:
def matchMe (s: String): Int = s match {
case "ichi" => 1
case "ni" => 2
case "san" => 3
case _ => -1
}
Java 2007 switch : .
Scala , , , :
trait Expr {
caseclass Num(value : int) extends Expr
caseclass Var(name : String) extends Expr
caseclass Mul(lft : Expr, rgt : Expr) extends Expr
}
...
// Simplification rule:
expr match {
case Mul(x, Num(1)) => x
case _ => e
}
C , , :
scala> val Entry = """(\w+)\s*=\s*(\d+)""".r
Entry: scala.util.matching.Regex = (\w+)\s*=\s*(\w+)
scala> def parse(s: String) = s match { case Entry(x,y) => (x, y) }
parse: (s: String)(String, Int)
scala> parse("salary=120")
res50: (String, Int) = (salary,120)
, , . , -, .
// a regular tree, not binary, Tree[X] = X + Tree[X]^nabstractclass Tree[X] // main class for a treecaseclass Leaf[X](v:X) extends Tree[X]
caseclass Branch[X](kids:List[Tree[X]]) extends Tree[X]
class TreeParser extends JavaTokenParsers {
// A tree is either a leaf or a branchprivate def node : Parser[Tree[String]] =
leaf | branch
// a branch is a sequence of trees in parentheses; // postprocessing consists of calling a constructorprivate def branch : Parser[Branch[String]] =
"("~repsep(node, ",")~")" ^^ { case "("~nodes~")" => Branch(List() ++ nodes) }
// a leaf is a string wrapped in a constructorprivate def leaf : Parser[Leaf[String]] =
string ^^ {case s => Leaf(s)}
// a string is a string is a stringprivate def string : Parser[String] = regex("""\w+""".r)
// this is all that's exposed
def read(input: CharSequence) = parseAll(node, input).get
}
def parseTree(input: CharSequence) = (new TreeParser).read(input)
scala> parse("(a,(b,(c,de,(),f)),g)")
res58: Tree[String] = Branch(List(Leaf(a), Branch(List(Leaf(b), Branch(List(Leaf(c), Leaf(de), Branch(List()), Leaf(f))))), Leaf(g)))
XML Scala
(, , ) , XML Scala , . :
class Person(val id: Int,
val firstName: String,
val lastName: String,
val title: String) {
def toXML = {
<person>
<id>{id}</id>
<firstName>{firstName}</firstName>
<lastName>{lastName}</lastName>
<title>{title}</title>
</person>
}
}
Scala
, , (. ., ), . . :
def qsort(list: List[Int]): List[Int] =
list match {
case Nil => Nil
case x::xs =>
qsort(xs.filter(_ < x)) :::
x ::
qsort(xs.filter(_ >= x))
}
, , , , ; , ; , ; , .
, :
> class Fact (n: Int) {
> def fact(n: Int): BigInt = if (n == 0) 1 else fact(n-1) * n
> def ! = fact(n)
> }
> implicit def int2fact(n: Int) = new Fact(n)
>
> println(42!)
1405006117752879898543142606244511569936384000000000
import org.scalatest.FlatSpec
import org.scalatest.matchers.ShouldMatchers
class StackSpec extends FlatSpec with ShouldMatchers {
"A Stack" should "pop values in LIFO order" in {
val stack = new Stack[Int]
stack.push(1)
stack.push(2)
stack.pop() should equal (2)
stack.pop() should equal (1)
}
it should "throw Exception on popping empty stack" in {
val emptyStack = new Stack[String]
evaluating { emptyStack.pop() }
should produce [NoSuchElementException]
}
}