Skip to content

Instantly share code, notes, and snippets.

View matemagyari's full-sized avatar

Mate Magyari matemagyari

View GitHub Profile
package org.home
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicInteger
import com.typesafe.scalalogging.StrictLogging
import scala.collection.immutable.Seq
import scala.collection.mutable.ListBuffer
import scala.concurrent.{ExecutionContext, Future}
val m1: StateMachine[String, Int] = Happy(5)
val m2: StateMachine[String, Int] = Happy(6)
//a function turning 2 integers into something. For the sake of example just an addition.
def combine(a: Int, b: Int): Int = a + b
//combine m1 and m2
val result1 = m1.flatMap(x ⇒ m2.map(y ⇒ combine(x, y)))
result1 shouldBe Happy(11)
val m1: StateMachine[String, Int] = Happy(5)
val m2: StateMachine[String, Int] = Happy(6)
//apply a simple Int => Int function to the StateMachine with map will keep it in happy state and transform its value
def plus10(a: Int): Int = a + 10
m1.map(plus10) shouldBe Happy(15)
//apply a simple Int => StateMachine[String, BigDecimal] function to the StateMachine with flatMap
//will possibly change its state and transform its value
def double(a: Int): StateMachine[String, BigDecimal] = Happy(new BigDecimal(2 * a))
sealed trait StateMachine[A, B] {
def map[C](f: B ⇒ C): StateMachine[A, C]
def flatMap[C](f: B ⇒ StateMachine[A, C]): StateMachine[A, C]
}
case class Unhappy[A, B](value: A) extends StateMachine[A, B] {
override def map[C](f: B ⇒ C) = Unhappy[A, C](value)
override def flatMap[C](f: B ⇒ StateMachine[A, C]) = Unhappy[A, C](value)
}
case class StateMachine[A, B] private(
private val unhappyValue: A,
private val happyValue: B) {
//one of them must be non-null, the other must be null
assert(Set[Any](unhappyValue, happyValue).filter(_ == null).size == 1)
def map[C](f: B ⇒ C): StateMachine2[A, C] = {
if (happyValue != null)
StateMachine.happy[A, C](f(happyValue))
object StateMachine {
def unhappy[A, B](unhappyValue: A): StateMachine[A, B] =
StateMachine[A, B](unhappyValue, null.asInstanceOf[B])
def happy[A, B](happyValue: B): StateMachine[A, B] =
StateMachine(null.asInstanceOf[A], happyValue)
}
case class StateMachine[A, B] private(
private val unhappyValue: A,
(ns home.async-play
(:require [clojure.core.async :as async]))
(defn long-comp1 [] 5)
(defn long-comp2 [] 6)
(defn aggregate [xs]
(println xs))
;;simple version, working with 2 functions
longComp1 := func() int {
return 5
}
longComp2 := func() int {
return 6
}
aggregate := func(is []int) {
fmt.Println(is)
//define a type for brevity below
type LongComp func() int
longComp1 := func() int {
return 5
}
longComp2 := func() int {
return 6
}
//assume these take time
def longComp1(): Int = 5
def longComp2(): Int = 6
def aggregate(i: Int, j: Int): Unit = {
println(s"i is $i, j is $j")
}
val longComp1Result = Future { longComp1() }
val longComp2Result = Future { longComp2() }