Skip to content

Instantly share code, notes, and snippets.

@yloiseau
Last active August 29, 2015 14:05
Show Gist options
  • Save yloiseau/776d64ad36147c78476e to your computer and use it in GitHub Desktop.
Save yloiseau/776d64ad36147c78476e to your computer and use it in GitHub Desktop.

improved

module memoizedeco

import java.lang.System

function memoizer = {
  var cache = map[]
  return |fun| {
    return |args...| {
        let key = [fun: hashCode(), Tuple(args)]
        if (not cache: containsKey(key)) {
          cache: add(key, fun: invokeWithArguments(args))
        }
        return cache: get(key)
    }
  }
}

let memo = memoizer()

@memo
function fib = |n| {
  if n <= 1 {
    return n
  } else {
    return fib(n - 1) + fib(n - 2)
  }
}

@memo
function foo = |n| -> n

local function run = {
  let start = System.currentTimeMillis()
  let result = fib(40)
  let duration = System.currentTimeMillis() - start
  println(">>> fib(40) = " + result + " (took " + duration + "ms)")
}

local function run2 = {
  let start = System.currentTimeMillis()
  let result = foo(40)
  let duration = System.currentTimeMillis() - start
  println(">>> foo(40) = " + result + " (took " + duration + "ms)")
}

function main = |args| {
  foreach i in range(0, 5) {
    println("run " + i)
    run()
    run2()
  }
}

Prints:

run 0
>>> fib(40) = 102334155 (took 234ms)
>>> foo(40) = 40 (took 15ms)
run 1
>>> fib(40) = 102334155 (took 3ms)
>>> foo(40) = 40 (took 2ms)
run 2
>>> fib(40) = 102334155 (took 1ms)
>>> foo(40) = 40 (took 1ms)
run 3
>>> fib(40) = 102334155 (took 1ms)
>>> foo(40) = 40 (took 1ms)
run 4
>>> fib(40) = 102334155 (took 1ms)
>>> foo(40) = 40 (took 1ms)

Yeah ! :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment