Reputation:
I don't actually know what to call this question. The title presented was the best I could come up with.
We are currently working with functional programming in Scala in school, and every so often there are a few instances where something just doesn't make sense in the way of things I am used to... A particular example is this:
type Rand[+A] = RNG => (A, RNG)
val int: Rand[Int] = _.nextInt
def unit[A](a: A): Rand[A] =
rng => (a, rng)
We are dealing with states here, trying to combat the repetition of having to transfer a new state to each function every time we are generating new random numbers using our RNG trait.
My question is this:
The lambda function expression defines the predicate "rng =>
" to be used as the place holder for our state. Normally what this predicate defines is clear such as with List.map(x => x)
where x is each element of the list. But it is not clear to me what rng
is here.
EDIT: I guess some people didn't understand the question so I will give some further examples here to clarify...
I'm not asking what Rand[A] is representing. I am asking what the received argument rng =>
is supposed to be interpreted as... For example
def map[A,B](l: List[A])(f: A => B): List[B] = ...
val l = List(1,2,3,4,5)
// l.map(x => x+1) -> List(2,3,4,5,6)
In the above map example, it is very easy to conceptually understand that the received argument x =>
given by the function argument f
is to be interpreted as each individual element of the list l
.
I am specifically looking for such a conceptual connection with rng =>
in unit
.
Upvotes: 0
Views: 367
Reputation: 51271
OK, I'll have a go at it.
def unit[A](a: A): Rand[A] = rng => (a, rng)
Here unit
takes one argument and builds half of a tuple. It returns the means to build the completed tuple.
val uHalf = unit('q') // this is the "a" parameter
Now, because of the definition of type Rand
(and uHalf
is of type Rand
) the other half of the tuple can only be of type RNG
, which isn't defined in your code example. But let's say you have a blob
of type RNG
handy.
val tup = uHalf(blob) // this is the "rng" parameter
Now you have the tuple ('q', blob)
.
You're right, in the example List(3,2,1).map(x => ...
, x
is the stand-in for values supplied from the List
. In the case of Rand
, rng
is the stand-in for a value (of type RNG
) to be supplied sometime/somewhere later in the code.
Upvotes: 3