Skip to content

Instantly share code, notes, and snippets.

View stasimus's full-sized avatar

Stas Shevchenko stasimus

  • ING
  • Netherlands
View GitHub Profile
type ListAnamorphism[U, T] = U => List[T]
def listAnamorphismFactory[U, T](func: T => Option[(U, T)]): ListAnamorphism[T, U] = {
in: T =>
def ana(initial: T): List[U] = func(initial) match {
case None => Nil
case Some((current, next)) => current :: ana(next)
}
class Parent {
x = 1;
show() {
alert(this.x);
}
}
class Child extends Parent {
x = 2;
public class Example {
private final int state;
public Example() {
try {
state = 5;
} catch (Exception e) {
state = -1;
}
}
val mapNResultWhenNull = Pair(p1, p2).mapN(stringPlus)
assertNull(mapNResultWhenNull)
val mapNResultNotNull = Pair(p2, p3).mapN(stringPlus)
assertNotNull(mapNResultNotNull)
assertEquals("p2p3", mapNResultNotNull)
/*
Semigroup's mapN for Pair
*/
fun <A, B> Pair<A?, A?>.mapN(func: (A, A) -> B?): B? =
this.first?.let { a1 -> this.second?.let { a2 -> func(a1, a2) } }
assertNull(p1?.flatMap { f -> p2.flatMap { s -> f + s } })
//or
val firstNullable = "param1".unit()?.flatMap { f -> null?.flatMap { f.plus(it) } }assertNull(firstNullable)
//or
val bothAreDefined = "param1".unit()?.flatMap { f -> "param2".unit()?.flatMap { f.plus(it) } }
assertEquals("param1param2", bothAreDefined)
/* From Scala
trait M[A] { def flatMap[B](f: A => M[B]): M[B] }
def unit[A](x: A): M[A]
*/
fun <A> A.unit(): A? = this
fun <A, B> A?.flatMap(func: (A) -> B?): B? =
if (this != null) func(this) else null
assertNull(concat3(p1, p2))
/* Welcome to primitive lambda calculus or http://callbackhell.com/ */
fun concat3(arg1: String?, arg2: String?): String? {
return arg1?.let { a1 -> arg2?.let { a2 -> a1 + a2 } }
}
@stasimus
stasimus / play3.kt
Last active November 13, 2018 12:59
val p1: String? = null
val p2: String? = "p2"
assertNull(concat2(p1, p2))
/* Almost ternary operator */
fun concat2(arg1: String?, arg2: String?): String? {
return if (arg1 != null && arg2 != null) arg1 + arg2 else null
}
def url(protocol: Option[String],
host: Option[String],
file: Option[String]): Option[URL] =
(protocol, host, file).mapN(new URL(_, _, _))