Skip to content

Instantly share code, notes, and snippets.

@stephenLee
stephenLee / Option.scala
Created September 20, 2012 05:13
Scala Option example
val capitals = Map("France" -> "Paris", "Japan" -> "Tokyo")
capitals get "France"
capitals get "North Pole"
def show(x: Option[String]) = x match {
case Some(x) => x
case None => "?"
}
show(capitals get "Japan")
@stephenLee
stephenLee / Option.scala
Created September 20, 2012 05:13
Scala Option example
val capitals = Map("France" -> "Paris", "Japan" -> "Tokyo")
capitals get "France"
capitals get "North Pole"
def show(x: Option[String]) = x match {
case Some(x) => x
case None => "?"
}
show(capitals get "Japan")
@stephenLee
stephenLee / Case.scala
Created September 20, 2012 00:47
Scala case class
abstract class Expr
case class Var(name: String) extends Expr
case class Number(num: Double) extends Expr
case class UnOp(operator: String, arg: Expr) extends Expr
case class BinOp(operator: String, left: Expr, right: Expr) extends Expr
val v = Var("x")
val op = BinOp("+", Number(1), v)
v.name
@stephenLee
stephenLee / Traits.scala
Created September 18, 2012 11:28
Scala Traits mixins example
import scala.collection.mutable.ArrayBuffer
//Abstract class IntQueue
abstract class IntQueue {
def get(): Int
def put(x: Int)
}
// A BasicIntQueue implemented with an ArrayBuffer
class BasicIntQueue extends IntQueue {
@stephenLee
stephenLee / Curried.scala
Created September 17, 2012 13:18
Defining and invoking a curried function.
def curriedSum(x: Int)(y: int) = x + y
curriedSum(1)(2) // 3
def first(x: Int) = (y: Int) => x + y
val second = first(1)
second(2) // 3
// use placeholder notation to use curriedSum in a partially applied function
@stephenLee
stephenLee / Partially.scala
Created September 17, 2012 12:28
Scala partially applied function demo
def sum(a: Int, b: Int, c: Int): Int = a + b + c
val a = sum _
a(1,2,3)
val b = sum(1, _: Int, 3)
b(2)
b(5)
@stephenLee
stephenLee / Repeated.scala
Created September 17, 2012 09:12
Scala repeated parameters demo
/**
* place an asterisk after the type of the parameter
*/
def echo(args: String*) =
for (arg <- args) printn(arg)
echo("hello", "world")
val arr = Array("What's", "up", "doc?")
echo(arr: _*)
@stephenLee
stephenLee / Rational.scala
Created September 17, 2012 06:10
Scala Rational class to illustrate functional objects
class Rational(n: Int, d: Int) {
require(d != 0)
private val g = gcd(n.abs, d.abs)
val number = n / g
val denom = d / g
def this(n: Int) = this(n, 1) // auxiliary constructor
def + (that: Rational): Rational =
@stephenLee
stephenLee / factorial.scala
Created September 13, 2012 13:43
non tail recursive version of factorial
def factorial(n: Int): Int = {
if (n==0) 1 else n * factorial(n-1)
}
@stephenLee
stephenLee / factorial.scala
Created September 13, 2012 13:34
tail-recursive version of factorial
def factorial(n: Int) = {
def factorial1(n: Int, multi: Int): Int = {
if (n == 0) multi
else factorial1(n-1, multi*n)
}
factorial1(n, 1)
}