Skip to content

Instantly share code, notes, and snippets.

def fib(n: Int): (Int, Int) = if (n==1) (1,1) else {
val (m1,m2) = fib(n-1)
(m2, m1+m2)
}
@tohenryliu
tohenryliu / timedFuture.scala
Last active August 29, 2015 14:13
TimedFuture
import scala.concurrent._
import scala.concurrent.duration._
object TimedFuture {
def apply[T](body: ⇒ T)(timeout: Duration = 10.seconds)(implicit executor: ExecutionContext): Future[T] = {
val start = System.currentTimeMillis()
Future {
val now = System.currentTimeMillis()
if (now - start > timeout.toMillis) throw new Exception(s"timed out after $timeout")
body
}
@tohenryliu
tohenryliu / Transactor.scala
Created January 10, 2015 02:53
thread safe transactions in an actor
object Transactions {
class Transactor(session: Session) extends BaseActor {
/**
* To be defined in child actors
*/
override def handleMessage: Receive = ???
def commit: Future[Unit] = ???
def rollback:Future[Unit] = ???
def execute[T](f: Session => T): Future[T] = ???
@tohenryliu
tohenryliu / gist:7a0df76d3672565da8ff
Last active August 29, 2015 14:10
battleship placement validator
object Battle {
import scala.util.Try
type cellType = String
type Result = Try[Set[Boat]]
val D = "D"
val W = " "
trait Boat {
def start: Point
@tohenryliu
tohenryliu / badUseOfLazyVal.scala
Created June 23, 2014 19:57
lazy val in def blocks
def test = {
lazy val x = {
println(s"lazy compute called")
Thread.sleep(1000*30)
1
}
x
}
def mRun = {
import scala.concurrent.ExecutionContext.Implicits.global
@tohenryliu
tohenryliu / auto-api.json
Created October 11, 2012 20:46
automate api action invoke
"
name, com.patch.kickass.actions.EmailPreferenceActions$SetOptOut
parameters: UserRef
param values: 1
"
"
output:
action name, param types, return type, case class, implementation(needed to invoke the action)
"
@tohenryliu
tohenryliu / versioning.scala
Created October 11, 2012 20:45
versioning idea
package versioning
// version 1 defined 2 actions here
trait V1 {
val SetOptOut = EmailPreferenceActions.SetOptOut
val GetSailthruEmail = EmailPreferenceActions.GetSailthruEmail
}
object V1Api extends V1
// version 2 need to replace SetOptOut with SetOptOutImproved
@tohenryliu
tohenryliu / gist:3287076
Created August 7, 2012 16:33
how to fail inside for comprehension of actionmonad
for{
u <- UserStore.getFull(requesterRef)
// .map{usr=> if(false) notAuthorizedC("x") else usr}
.map{usr=>UserRefs.ById(usr.id)}
// _ <- if (u.status == Statuses.Active) success
// else notAuthorizedC("Unable to retrieve the permissions for post: [%s] and requester: [%s]".format(postRef, requesterRef))
r <- postRef match {
case ref:PostRefs.ById =>
getPermitedOperationsForPostsById(Set(ref), u)
.map[ReaderCtx, Set[Operation]]{r=> r(ref)}