Skip to content

Instantly share code, notes, and snippets.

View debasishg's full-sized avatar
🏠
Working from home

Debasish Ghosh debasishg

🏠
Working from home
View GitHub Profile
@debasishg
debasishg / gist:f14fd21a8ef14a35e65e
Created October 10, 2014 01:28
generator and property for ADTs with custom initialization logic
// the ADT
sealed trait Account {
def no: String
def name: String
def openingDate: Date
def closeDate: Option[Date]
}
final case class CheckingAccount private[prop](no: String, name: String, openingDate: Date, closeDate: Option[Date])
sealed trait Base
case class D1(...) extends Base
case class D2(...) extedns Base
// Have defined all instances of EncodeJson & DecodeJson for D1 and D2
// works in 6.0.x but does not compile in 6.1-M5 since DecodeResult is now invariant
implicit val decode: DecodeJson[Base] = DecodeJson { c =>
(c --\ "storeDelete").as[D1] |||
(c --\ "indexState").as[D2] |||
trait AccountRepository {
def query(no: String): \/[NonEmptyList[String], Option[Account]]
def store(a: Account): \/[NonEmptyList[String], Account]
def query(openedOn: Date): \/[NonEmptyList[String], Seq[Account]]
def all: \/[NonEmptyList[String], Seq[Account]]
}
/**
* and an implementation for this trait
**/
trait Writes[T] {
def writes(o: T): JsValue
}
trait Reads[T] {
def reads(json: JsValue): T
}
trait Format[T] extends Writes[T] with Reads[T]
Welcome to Scala version 2.11.5 (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_65).
Type in expressions to have them evaluated.
Type :help for more information.
scala> import frdomain.ch3.repository._
import frdomain.ch3.repository._
scala> import reader._
import reader._
@debasishg
debasishg / gist:67b16a1aa941586b7c43
Created July 4, 2015 20:53
Generalizing the definition of an F-algebra in Scala
/**
* http://stackoverflow.com/questions/16015020/what-does-coalgebra-mean-in-the-context-of-programming
**/
def op[T: Monoid](arg: \/[(T, T), T]): T = {
val m = implicitly[Monoid[T]]
arg match {
case -\/((a, b)) => m.append(a, b)
case \/-(a) => m.zero
}
}
val c1 = new PubSubClient("foo", r)
c1.start
val c2 = new PubSubClient("bar", t)
c2.start
val server = new PubSubServer
server.start
server ! Subscribe(c1, List("a", "b", "c"))
server ! Publish(c2, "a", "hello")
server ! Publish(c2, "c", "hi")
object Sub {
println("starting subscription service ..")
val s = new Subscriber(new RedisClient("localhost", 6379))
s.start
s ! Register(callback)
def sub(channels: String*) = {
s ! Subscribe(channels.toArray)
}
def callback(pubsub: PubSubMessage) = pubsub match {
case S(channel, no) => println("subscribed to " + channel + " and count = " + no)
case U(channel, no) => println("unsubscribed from " + channel + " and count = " + no)
case M(channel, msg) =>
msg match {
// exit will unsubscribe from all channels and stop subscription service
case "exit" =>
println("unsubscribe all ..")
r.unsubscribe
1. Download redis from http://github.com/antirez/redis
2. build using "make"
3. Run server as ./redis-server