juan_gandhi: (Default)
2025-05-03 05:51 pm
Entry tags:

minimalistic cache

isFinite tells us whether we can cache it; maybe it's coming from a predicate that checks the size, or something.


class Cache[K,V](isFinite: Boolean, build: K => V):
  private val cache: mutable.Map[K, V] = mutable.Map[K, V]()

  private val app: K => V = if (isFinite) (k: K) => cache.getOrElseUpdate(k, build(k)) else (k: K) => build(k)
  
  inline def apply(k: K): V = app(k)

juan_gandhi: (VP)
2016-04-07 11:43 am
Entry tags:

dealing with time

Here's the essence of cache as I wrote about earlier tonight.

trait TimeReader {

  def currentTime: Long = System.currentTimeMillis

  def flowOfTime = Iterator.iterate(currentTime){_ => currentTime}

  def interval(n:Long) = {
    flowOfTime.next // the first drop, may be stale
    val end = flowOfTime.next + n
    flowOfTime takeWhile (end >)
  }

  def interval(duration: Duration) = interval(duration.toMillis)
  //...


Note that you can override currentTime
for {
value <- readFromSource
t <- interval(60 seconds)
} useThisValue(value)


e.g.
for {i <- 1 to 10; t <- interval(1 second) } {Thread.sleep(1); println(s"$i @$t") }
juan_gandhi: (VP)
2016-04-07 11:30 am
Entry tags:

cache is cartesian product of two iterators (not sure about streams)

I'm totally excited with this idea; it looks like either nobody got it, or it is totally obvious.
It was not obvious to me until last night.
juan_gandhi: (Default)
2012-05-10 10:44 pm
Entry tags:

started git project "scala kittens"

Posted just one small class, Caching.
here

Already posted the first version of Caching here; seems like it requires a blog entry with explanations... or no? It contains a couple of tricks and one questionable solution...