0

I was reading an article at https://medium.com/@aarshkshah1992/scala-functional-memoization-and-lazy-loading-caches-de116f24828

and this part is really interesting

def memoizedIsPrime: Int => Boolean = {
  def checkIfPrime(i: Int): Boolean = {
    2 to (i - 1) forall (x => i % x != 0)
  }

  var cache = Map.empty[Int, Boolean]
  i => {
    if (!cache.contains(i)) {
      print(s"Calling isPrime since input ${i} has not been seen before and caching the output")
      cache = cache updated(i, checkIfPrime(i))
    }
    else print(s"Input ${i} has been seen before , returning cached output")
    cache(i)
  }
}

val isPrime = memoizedIsPrime

Can anyone explain how i is being accessed and the how the code part after => is really working?

Thanks in advance :)

1 Answer 1

2

The result of memoizedIsPrime is Int => Boolean, in other words a function that takes an Int and returns a Boolean.

So in the body of the code, after we get some preliminary def and val definitions out of the way, we need a way to reference the incoming Int:

i => ...

OK, so it is decided, we'll refer to the received Int as i. Now we need to produce a Boolean value. And that, of course, is the { } delimited block of code that comes after the => which gets executed every time a new Int arrives.

Sign up to request clarification or add additional context in comments.

3 Comments

What if memoizedIsPrime took multiple parameters? would it be (i, j)?
A memoized function of arity 2 would create a 2-tuple with the received parameter values and use that tuple as the key to the cache lookup.
Tried. Thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.