Skip to content

Instantly share code, notes, and snippets.

View bmarcot's full-sized avatar

Benoit Marcot bmarcot

  • Trondheim
View GitHub Profile
case class Order(val id: Int, val card: Int, val address: String)
// val m = (for (i <- 1 to 4) yield Order(i)) zip List(1, 1, 2, 3)
// m.groupBy(_._2)
val orders = (for {
order <- List(Order(1, 46459, "3, calle Brazil, Torremolinos"),
Order(2, 85475, "102, av JB Clement, Boulogne"),
Order(1, 78545, "1, Paradize Bvld., Palo Alto"))
} yield (order, order.id))
@bmarcot
bmarcot / for_comprehension.scala
Last active December 16, 2015 22:39
For-comprehension
def f(xs: List[Int]): List[List[(Int, Int)]] = {
xs match {
case Nil => List(List())
case x :: xs => for {
ns <- f(xs)
i <- 0 to x
} yield (x, i) :: ns
}
}
@bmarcot
bmarcot / epfl_wk_6_3.scala
Last active December 16, 2015 19:49
The ``N Queens'' problem in Scala.
def queens(n: Int): Set[List[Int]] = {
def isSafe(col: Int, queens: List[Int]): Boolean = {
val row = queens.length
val queensWithRow = queens zip (row - 1 to 0 by -1)
queensWithRow.forall {
case (c, r) => c != col && (math.abs(col - c) != row - r)
}
}
def ScalarProduct(xs: List[Double], ys: List[Double]): Double =
(for ((x, y) <- xs zip ys) yield x * y).sum
def isPrime(n: Int): Boolean = (2 to n - 1).forall(x => n % x != 0)
def mapFun[T, U](xs: List[T], f: T => U): List[U] = (xs foldRight List[U]())(f(_) :: _)
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)
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
// 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
}
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))
}