Nitish Upreti
Nitish Upreti

Reputation: 6550

Writing a Scala function that returns a function when invoked

Assuming a typical hash function for a value x :

h(x) = ( a * x + b ) % R

I want to write a scala function say buildHashFunction that returns a new hashFunction ( using random values of a and b) every time it is executed. R can be hardcoded to be the same.

The idea is to then use the resulting hashFunction to deterministically calculate hash of a number.

Upvotes: 0

Views: 96

Answers (1)

lmm
lmm

Reputation: 17431

The most obvious way to do this will work fine:

val r = new SecureRandom()
val R = r.nextInt()

def buildHashFunction(): Int => Int = {      
  val a = r.nextInt()
  val b = r.nextInt()
  def hashFunction(x: Int) =
    ( a * x + b ) % R

  hashFunction
}

Upvotes: 3

Related Questions