Skip to content

Instantly share code, notes, and snippets.

View bmarcot's full-sized avatar

Benoit Marcot bmarcot

  • Trondheim
View GitHub Profile
@bmarcot
bmarcot / json.rb
Created November 4, 2014 17:58
To include any methods on the model, use :methods.
class Content
def type
self.class.name
end
end
class TwitterContent
def type
"twitter"
end
var str = 'allleee #psG !! tudu';
var regex = /#(\w+)/;
str = str.replace(regex, "<b>#$1</b>");
import scala.util.Random.nextInt
def choosePivot(xs: List[Int]): Int = {
if (xs.isEmpty) 0
else xs(nextInt(xs.length))
}
def quicksort(xs: List[Int], p: Int): List[Int] = {
if (xs.isEmpty) List()
else if (xs.length == 1) xs
@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
}