Skip to content

Instantly share code, notes, and snippets.

View bmarcot's full-sized avatar

Benoit Marcot bmarcot

  • Trondheim
View GitHub Profile
@bmarcot
bmarcot / ex_5_2_1.scala
Last active December 15, 2015 12:59
Scala By Example
import scala.annotation.tailrec
def sum(f: Int => Int)(a: Int, b: Int) : Int = {
@tailrec
def iter(a: Int, result: Int) : Int = {
if (a > b) result
else iter(a + 1, f(a) + result)
}
iter(a, 0)
}
@bmarcot
bmarcot / ex_5_2_2.scala
Last active December 15, 2015 12:59
Scala By Example
import scala.annotation.tailrec
def product(f: Int => Int)(a: Int, b: Int) : Int = {
@tailrec
def iter(a: Int, result: Int) : Int = {
if (a > b) result
else iter(a + 1, f(a) * result)
}
iter(a, 0)
}
@bmarcot
bmarcot / ex_5_2_4.scala
Created March 28, 2013 15:38
Scala By Example -- usage: compute((x, y) => x * y)(x => x)(1, 3)
import scala.annotation.tailrec
def compute(op: (Int, Int) => Int)(f: Int => Int)(a: Int, b: Int) : Int = {
@tailrec
def iter(a: Int, result: Int) : Int = {
if (a > b) result
else iter(a + 1, op(f(a), result))
}
iter(a + 1, f(a))
}
abstract class IntSet {
def isEmpty: Boolean
def contains(x: Int): Boolean
def include(x: Int): IntSet
def union(other: IntSet): IntSet
}
class EmptySet extends IntSet {
def isEmpty = true
def contains(x: Int): Boolean = false
trait List[T] {
def isEmpty: Boolean
def head: T
def tail: List[T]
}
class Cons[T](val head: T, val tail: List[T]) extends List[T] {
def isEmpty: Boolean = false
}
object List {
// List()
def apply[T]() = new Nil
// List(1)
def apply[T](x1: T): List[T] = new Cons(x1, new Nil)
// List(1, 2)
def apply[T](x1: T, x2: T): List[T] = new Cons(x1, new Cons(x2, new Nil))
}
// Peano numbers
abstract class Nat {
def isZero: Boolean
def predecessor: Nat
def successor: Nat = new Succ(this)
def + (that: Nat): Nat
def - (that: Nat): Nat
}
Then /I should see "(.*)" before "(.*)"/ do |e1, e2|
# ensure that that e1 occurs before e2.
# page.body is the entire content of the page as a string.
assert page.body.index(e1) < page.body.index(e2)
end
Then /I should see "(.*)" before "(.*)"/ do |e1, e2|
# another strategy with regex (see Hints part of the assignments)
page.body.scan(/.*"#{e1}".*"#{e2}".*/).length.should == 1
end
def squareList(xs: List[Int]): List[Int] = xs match {
case Nil => Nil
case y :: ys => y * y :: squareList(ys)
}
def squareList(xs: List[Int]): List[Int] = xs map (y => y * y)
def mapFun[T, U](xs: List[T], f: T => U): List[U] = (xs foldRight List[U]())(f(_) :: _)