Skip to content

Instantly share code, notes, and snippets.

View stoyle's full-sized avatar

Alf Kristian Støyle stoyle

View GitHub Profile
@stoyle
stoyle / fibonacci.scala
Created June 13, 2011 13:09
Fibonacci manipulation with parallel collections, tail recursion, lazy evaluation and memoization
// Definitions:
def t(f: => Any) { val start = System.currentTimeMillis; val res = f; println("Time: " + (System.currentTimeMillis - start) + "ms"); res}
// "Vanilla" version
def fib(num: Long): Long = if (num < 2) num else fib(num - 1) + fib(num - 2)
// Tail recursive version
def fibTR(num: Long) = {
@scala.annotation.tailrec
def fibtr(n: Long, nxt: Long, res: Long): Long = if (n == 0) res else fibtr(n - 1, res + nxt, nxt)
@stoyle
stoyle / scala_parallel_collections_demo.scala
Created April 14, 2011 10:11
Demoing parallel collections in Scala 2.9.0.RC1 REPL, on a MacBook Pro, 2.66 GHz Intel Core 2 Duo
~ $ scala
Welcome to Scala version 2.9.0.RC1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_24).
Type in expressions to have them evaluated.
Type :help for more information.
scala> def time(work: => Any) { val start = System.currentTimeMillis; work; println("Time: " + (System.currentTimeMillis - start) + "ms")}
time: (work: => Any)Unit
scala> time(Thread.sleep(10))
Time: 11ms
(defn transfer [from-account to-account amount]
(dosync
(if (> amount @(:balance from-account))
(throw (new Exception "Not enough money!")))
(alter (:balance from-account) - amount)
(alter (:balance to-account) + amount)))
(defrecord Account [account-no balance])
(def account-a (Account. 1 (ref 1000)))
import reflect.Manifest
object CucumberScalaDsl extends Application {
/* Revision. Does not work because Manifest.classType uses erased types.
Hence you will get a ClassCastException when using a double in stead of an integer for example.
Thanks fredriv for spotting this!
type stringFunction = Function1[String, Unit]
type intStringFunction = Function2[Int, String, Unit]