Skip to content

Instantly share code, notes, and snippets.

@aryairani
aryairani / Factorial.scala
Created October 10, 2012 18:40
Factorial in Scala
object Factorial {
implicit class LongFactorialPimp(x: Long) {
require(x >= 0)
def ! : Long = {
if (x < 2) 1
else x * ((x-1)!) // ! has the wrong precedence compared to * :(
}
}
println(11!)
}
// scalaVersion := "2.10.0-RC5"
// libraryDependencies += "org.scalaz" %% "scalaz-core" % "7.0.0-M6" cross CrossVersion.full
import scalaz.{OptionT,Writer}
type Issue = String
type ListWriter[+A] = Writer[List[Issue],A]
type Box[+A] = OptionT[ListWriter,A]
object EmptyBox {
def unapply[A](b: Box[A]): Option[List[Issue]] =
trait SuperC[A,B] {
def getB(a: A): B
// ...
}
trait Foo {
type A
type B
type C <: SuperC[A,B]
// ...
trait AbstractAgent[S,A] {
type Self = AbstractAgent[S,A]
def learn(s: S): Self
}
trait GameDomain {
type State
type Action
type Agent <: AbstractAgent[State, Action]
}
// Foo can be extended, and `step` should return the extended type
trait Foo[S,A] {
type Self = Foo[S,A]
def step(s: S): Self
}
// Bar can be extended, fixing a more specific F
trait Bar {
type S
type A
@aryairani
aryairani / RightToLeftInference.scala
Last active December 10, 2015 02:18
Why is the type inferred for f1 but not for f2?
implicit class Provided[A](f: A => A) {
def provided(c: A => Boolean): A => A =
a => if (c(a)) f(a) else a
def ->:(c: A => Boolean) = provided(c)
def <--(c: A => Boolean) = provided(c)
}
def add(x: Int) = (_:Int) + x
val f1 = add(3) <-- (_ < 5)
[alias]
lol = log --graph --decorate --pretty=oneline --abbrev-commit
lola = log --graph --decorate --pretty=oneline --abbrev-commit --all
class Original<K,V> {
public V get(final K key)
{
Session s;
try {
s = oGrid.getSession();
ObjectMap map = s.getMap(cacheName);
return (V) map.get(key);
}
catch (ObjectGridException oge)
implicit class RichProperties(properties: Properties) {
import scalaz.syntax.std.boolean._
def getIfTrue[T](key: String, value: => T) =
(properties.get(key) == "true").option(value)
}
val l = List("a","b","c","d")
val getStyle = (k: Int) => l(k % l.length)
val styles = List.tabulate(10)(getStyle)
// styles: List[String] = List(a, b, c, d, a, b, c, d, a, b)
// or
def getStyle[A](styles: Seq[A]) = (k: Int) => styles(k % styles.length)
val l2 = List(1, 5, 9)
val styles = List.tabulate(10)(getStyle(l2))