Skip to content

Instantly share code, notes, and snippets.

View stasimus's full-sized avatar

Stas Shevchenko stasimus

  • ING
  • Netherlands
View GitHub Profile
@stasimus
stasimus / TestClass.scala
Created June 7, 2012 10:55
Tracing around call, catching exceptions
class TestClass {
def func(inFunc: => Unit) {
println("Before")
try { inFunc }
catch { case _ => }
println("After")
}
}
@stasimus
stasimus / Program.scala
Created June 7, 2012 11:04
closure with implicit return
object Program {
def main(args: Array[String]) {
val obj = new TestClass
obj func { println("inside") }
}
}
@stasimus
stasimus / Program.scala
Created June 7, 2012 13:48
Explicit return
object Program {
def main(args: Array[String]) {
val obj = new TestClass
obj func { println("inside"); return }
}
}
@stasimus
stasimus / isGreater.scala
Created June 7, 2012 14:23
return from closure
def isGreate0(list:List[Int]):Boolean = {
for (i <- list)
if (i <= 0)
return false
true
}
trait Semigroup[A] {
def append(a1: A, a2: A): A
}
sealed abstract class Validation[F: Semigroup] {
final def and(other: Validation[F]) = (this, other) match {
case (Failure(e1), Failure(e2)) => Failure(implicitly[Semigroup[F]].append(e1, e2))
case (Failure(e1), Success()) => Failure(e1)
case (Success(), Failure(e2)) => Failure(e2)
case (Success(), Success()) => Success
implicit val listSemigroup = new Semigroup[List[String]] {
def append(a1: List[String], a2: List[String]): List[String] = {
a1 ::: a2
}
}
case class Weapon(name: String, ammo: Long)
case class Soldier(rank: Int, weapon: Weapon)
case class Lens[R, F](get: R => F, set: (R, F) => R) {
def compose[Q](g: Lens[Q, R]): Lens[Q, F] =
Lens(get = get compose g.get,
set = (q, f) => g set(q, set(g get q, f)))
}
def validateAmmo(ammo: => Long): Validation[List[String]] = {
if (ammo > 0) Success[List[String]]()
else Failure(List("Negative ammo"))
}
def validateName(name: => String): Validation[List[String]] = {
if (!name.isEmpty) Success[List[String]]()
else Failure(List("Empty Name"))
}
val blaster = new Weapon("", -99)
val soldier = new Soldier(4, blaster)
val validationR = validateAmmo(soldierAmmoL.get(soldier)) and validateName(soldierWeaponName.get(soldier))
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>${groovy.version}</version>
</dependency>