Skip to content

Instantly share code, notes, and snippets.

View Krasnyanskiy's full-sized avatar

Sasha Krasnyanskiy

  • Cupertino, California
View GitHub Profile
@Krasnyanskiy
Krasnyanskiy / Application.scala
Last active April 4, 2016 23:48
-scala: foldr
val words = List("a", "b", "c", "d", "a", "c", "b", "a", "b", "d")
val res0 = words.map(w => (w, 1)).foldRight(("", 1)) {
case ((x1, y1), (x2, y2)) => (x1 + x2, y1 + y2)
}
@Krasnyanskiy
Krasnyanskiy / ReflectionUtils.java
Last active April 7, 2016 20:02
-java: object type
public ObjectType getObjectType(Object object) {
if (object instanceof Map) return MAP;
else if (object instanceof Collection) return COLLECTION;
else if (object instanceof Integer) return INT;
else if (object instanceof Byte) return BYTE;
else if (object instanceof Boolean) return BOOL;
else if (object instanceof int[]) return INT_ARRAY;
else if (object instanceof char[]) return CHAR_ARRAY;
else if (object instanceof byte[]) return BYTE_ARRAY;
@Krasnyanskiy
Krasnyanskiy / CastApp.java
Last active April 9, 2016 17:37
-java: array types
int[] ints = {1, 2, 3, 4, 5, 6};
Object[] objects = (Object[]) ints; // error! cannot cast int[] to Object[]
@Krasnyanskiy
Krasnyanskiy / FoldDemo.scala
Created April 16, 2016 16:09
-scala: flatMap
abstract class List[+T] {
def flatMap[U](f: T => List[U]): List[U] = this match {
case x :: xs => f(x) ++ xs.flatMap(f) // ++ is a concat operator
case Nil => Nil
}
}
@Krasnyanskiy
Krasnyanskiy / FMap.scala
Last active April 16, 2016 18:17
-scala: fMap
val opt: Option[Int] = Some(1)
val r3 = opt flatMap {
case (x: Int) => Some(x+1)
case _ => None
}
@Krasnyanskiy
Krasnyanskiy / Test.scala
Last active April 16, 2016 19:25
-scala: ?
object Test {
def main(args: Array[String]) {
val result = `iterate'`(3, `^2`, 5)
println(s"$result")
}
def `iterate'`(n: Int, f: Int => Int, x: Int): Int = n match {
case 0 => x
case _ => `iterate'`(n - 1, f, f(x))
@Krasnyanskiy
Krasnyanskiy / WhileLoop.scala
Last active April 17, 2016 13:42
-scala: while -> recursive
def `while`(condition: => Boolean)(command: => Unit): Unit = if (condition) {
command
`while`(condition)(command)
}
var i = 10
`while`{ i = i - 1; i > 0 } { println(i) }
@Krasnyanskiy
Krasnyanskiy / WhileApp.scala
Last active April 17, 2016 14:13
-scala: fixme (!)
var i = 10
class Condition(closure: (=> Unit) => Condition)(cmd: => Unit) {
def until(condition: => Boolean) = {
if (condition) {
cmd
closure(cmd)
}
}
@Krasnyanskiy
Krasnyanskiy / Application.scala
Created April 21, 2016 11:01
-scala: PF with closure
val f: PartialFunction[Int, Boolean] = {
case 1 => true
case 2 => true
case 3 => true
}
println {
f.applyOrElse(7, (_: Int) => false)
}
@Krasnyanskiy
Krasnyanskiy / Application.scala
Last active April 21, 2016 11:07
-scala: function composing
val f: PartialFunction[Int, Boolean] = {
case 1 => true
case 2 => true
case 3 => true
}
val g: PartialFunction[Boolean, Int] = {
case true => 1
case false => 2
}