Below is some really rudimentary sample code to illustrate the question.
case class randomizer(seed: Long){
def getRandom(): Double = {
//Other stuff
val rand = new util.Random(seed)
rand.nextDouble()
}
}
This will reliably return the same first value always. Every time getRandom is called.
However,
case class randomizer(seed: Long){
val rand = new util.Random(seed)
def getRandom(): Double = {
//Other stuff
rand.nextDouble()
}
}
This will return a different random value every time.
I suspect this is because by re-initializing rand every single time (as in the first one) we end up getting the first number for that seed. Since the seed guarantees that we will get the same "set" of random numbers each time this is expected behavior. By moving the generator outside of the function it will exist as long as the class does, and as a result continue generating numbers in that "set". Is this the correct way to think about this?
It's not a "set" so much as a "stream", but yes, that's it.
Related
My code looks like:
case class SRecord(trialId: String, private var _max:Int) {
def max=_max
def max_=(value:Int):Unit=_max=value
}
Then later on I apply a function onto it:
def groupSummaryRecords(it:Iterator[Option[SRecord]], optionSummary:Option[SRecord]):Option[SRecord] = {
var max=0;
var sRecord1 : Option[SRecord] = None
var i=0
while(it.hasNext) {
var sRecord:Option[SRecord] = it.next();
if(i==0) {
sRecord1 = sRecord;
}
..
}
sRecord1.max=max; // getting 'reassignment to val' compilation error
..
}
Why am i getting this compilation error, and how to fix it ?
If I instead change sRecord and sRecord1 instances to be of type SRecord instead of Option[SRecord] as well as the method signature, it all works fine however.
But in some cases I may have a null SRecord hence the use of None/Some. I am new to Scala, using Option/Some all over feels like a real pain if you ask me, i am just thinking of removing all this Option nonsense and testing for 'null' in good ol' Java, at least my code would work ??!
With the line sRecord1.max=max you are trying to call the max method on an Option[SRecord], not an SRecord. You want to access the contained SRecord (if any) and call the method on that, which can be done using foreach:
sRecord1.foreach(_.max=max)
which is desugared to:
sRecord1.foreach( srec => srec.max=max )
(the actual name "srec" is made up, the compiler will assign some internal name, but you get the idea). If sRecord1 is None, this won't do anything, but if it is Some(srec), the method execution will be passed in to operate on the contained instance.
I'm completely new to Lift. My goal is to make a small application which will let me enter data about scientific articles (studies) into a database.
I haven't gotten around to making a database yet, still playing with getting an entry form to work. So I decided that I will hold a few studies in memory, in a list of a companion object to the Study class. I also created an accumulator variable to dispense unique IDs, as long as I don't have a DBMS managing the IDs.
As a smoke test, I visited the page showing the list of studies (seeded with two studies in code), then visited the form page, entered a new study, and navigated again to the list of studies. I was surprised to see that my new study has the ID of 1 instead of 3, so at some point, my accumulator variable must have been reset. But the ListBuffer collecting studies was not reset, because it showed all three studies. Adding more studies results in the counter incrementing by 1 every time.
The literature I have found on Lift (the two free books on Liftweb, as well as Gilberto Garcia's Lift Application Development Cookbook) are incomplete and are more like a collection of mini-tutorials, they don't explain how Lift works.
So what is the actual lifecycle of my Study object, and why did one mutable variable get reset after re-opening the page but not another?
package org.rumtscho.litsuche
package study
import scala.collection.mutable.ListBuffer
class Study private[study](
val id: Int,
val handmadeAuthorRef: String,
val humanReadableDescription: String )
{
}
object Study {
val seedStudies = List(
new Study(dispenseNextFreeId, "Brooks1975", "Tells us that throwing more programmers at a project makes it run late, not early"),
new Study(dispenseNextFreeId, "Dijkstra1968", "Recognizes that we need structured code")
)
private var studiesList = seedStudies.to[ListBuffer]
private var currentId = 0
private def dispenseNextFreeId: Int = {
currentId = currentId + 1
return currentId
}
def allStudies = studiesList.toList
def addStudy(reference: String, description: String): Unit = {
studiesList += new Study(dispenseNextFreeId, reference, description)
}
}
Here is the representation of the three studies:
update My understanding of what is happening (could be wrong, of course):
I open the page showing the list of studies. This calls allStudies. studiesList is initialized to contain Brooks1975 and Dijkstra1968. During the construction of the studies, currentId is initialized to 0 and then incremented to 2.
I open the entry form and add a third study. addStudy retrieves allStudies from memory, without initializing it again. It initializes currentId to 0. I end up with a third study with the ID 1.
I display all studies, then return to the entry form page. This time, addStudy retrieves both allStudies and currentId from memory. I get a fourth study with the ID of 2.
The comments have pointed out that this is probably Scala-specific and not related to Lift. But still, I don't understand why currentId is initialized two times (in steps 1 and 2), and not either once (as soon as the object itself is created) or every time it is read. I would have expected the first behavior, but even reinitializing every time seems more logical than randomly reinitializing one time only.
Go into the scala REPL, enter paste mode (:paste) command, and put in the following:
def increment {
currentId = currentId + 1
}
increment
increment
var currentId = 0
then try
var currentId = 0
def increment {
currentId = currentId + 1
}
increment
increment
In the first example, currentId ends up with value 0. In the second, it ends up with value 2. Why does this happen? I'm not an expert on Scala declaration, but it seems that this is the same problem you are running in to.
It seems that the solution is as #jcern suggests. In general, I'd say put all your declarations at the top of your classes or objects, and always declare before using a variable, and not the other way around.
In my function, can I have a variable that
Retains its value between function calls.
Is only visible inside that function
Is unique for each thread i.e. if I'm calling the function from two threads then there are two variables that are static with regard to each thread.
Why I want that:
I have a function in which I fill in a list and return that list. The problem is that if I declare a variable normally, then I will have to allocate memory for it every time I call the function. I want to avoid that and allocate only once then every time I call the function it would fill in that variable with the proper values then return it.
I can do the following inside a class:
class MyClass {
val __readLineTemp = mutable.IndexedSeq.fill[Int](5)(-1)
def readLine() = {
var i = 0
while (i < __readLineTemp.length)
{
__readLineTemp(i) = Random.nextInt()
i += 1
}
__readLineTemp
}
}
My problems with this approach is that it doesn't satisfy the points 2 and 3 namely visibility only inside the method and being unique for each thread. However, for point 3 I can simply make each thread initialise its own object of MyClass.
I understand there is probably no way of achieving exactly what I want, but sometimes people come up with clever ideas to overcome this, specially that Scala seems quite deep and there is a lot of tricks you can do
You can use a closure to satisfy 1 and 2:
def foo = {
var a = 5
() => {
a = a + 1
a
}
}
i.e. create a closure that will contain the static variable (in your case, this is __readLineTemp) and return a function that's the only thing with access to the variable.
Then use it like this to satisfy the thread requirement:
val t1 = new Thread(new Runnable {
def run = {
val f = new DynamicVariable(foo)
println(f.value())
println(f.value())
}
})
I have a procedure that continuously updates a value. I want to be able to periodically query the operation for the current value. In my particular example, every update can be considered an improvement and the procedure will eventually converge on a final, best answer, but I want/need access to the intermediate results. The speed with which the loop executes and the time it takes to converge matters.
As an example, consider this loop:
var current = 0
while(current < 100){
current = current + 1
}
I want to be able to get value of current on any loop iteration.
A solution with an Actor would be:
class UpdatingActor extends Actor{
var current : Int = 0
def receive = {
case Update => {
current = current + 1
if (current < 100) self ! Update
}
case Query => sender ! current
}
}
You could get rid of the var using become or FSM, but this example is more clear IMO.
Alternatively, one actor could run the operation and send updated results on every loop iteration to another actor, whose sole responsibility is updating the value and responding to queries about it. I don't know much about "agents" in Akka, but this seems like a potential use case for one.
What are better/alternative ways of doing this using Scala? I don't need to use actors; that was just one solution that came to mind.
Your actor-based solution is ok.
Sending the intermediate result after each change to a "result provider" actor would be a good idea as well if the calculation blocks the actor for a long time and you want to make sure that you can always get the intermediate result. Another alternative would be to make the actual calculator actor a child of the actor that collects the best result. That way the thing acts as a single actor from the outside, and you have the actor that has state (the current best result) separated from the actor that does the computation, which might fail.
An agent would be a solution somewhat between the very low level #volatile/AtomicInteger approach and an Actor. An agent is something that can only be modified by running a transform on it (and there is a queue for transforms), but which has a current state that can always be accessed. It is not location transparent though. so stay with the actor approach if you need that.
Here is how you would solve this with an agent. You have one thread which does a long-running calculation (simulated by Thread.sleep) and another thread that just prints out the best current result in regular intervals (also simulated by Thread.sleep).
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.duration._
import scala.concurrent._
import akka.agent.Agent
object Main extends App {
val agent = Agent(0)
def computation() : Unit = {
for(i<-0 until 100) {
agent.send { current =>
Thread.sleep(1000) // to simulate a long-running computation
current + 1
}
}
}
def watch() : Unit = {
while(true) {
println("Current value is " + agent.get)
Thread.sleep(1000)
}
}
global.execute(new Runnable {
def run() = computation
})
watch()
}
But all in all I think an actor-based solution would be superior. For example you could do the calculation on a different machine than the result tracking.
The scope of the question is a little wide, but I'll try :)
First, your example is perfectly fine, I don't see the point of getting rid of the var. This is what actors are for: protect mutable state.
Second, based on what you describe you don't need an actor at all.
class UpdatingActor {
private var current = 0
def startCrazyJob() {
while(current < 100){
current = current + 1
}
}
def soWhatsGoingOn: Int = current
}
You just need one thread to call startCrazyJob and a second one that will periodically call soWhatsGoingOn.
IMHO, the actor approach is better, but it's up to you to decide if it's worth importing the akka library just for this use case.
Long time java programmer slowly learning scala (loving it by the way), and I think my mind is still wrapping itself around the concept of writing things functionally. Right now I'm attempting to write a simple visualizer for some moving 2d textures. The imperative approach is simple enough, and I'm sure most of you will recognize this relatively ubiquitous block of code (stuff was changed to protect the innocent):
class MovingTexture(var position, var velocity) extends Renders with Advances {
def render : Unit = {...}
def advance(milliseconds : Float) : Unit = {
position = position + velocity * milliseconds
}
}
This code will work just fine, however it has tons of mutable state and its functions are replete with side effects. I can't let myself get away with this, there must be a better way!
Does anyone have an amazing, elegant, functional solution to this simple problem? Does anyone know of a source where I could learn more about solving these sorts of problems?
There's way more to this answer than can be fit in the space of one stackoverflow response, but the best and most complete answer to questions like this is to use something called Functional Reactive Programming. The basic idea is to represent each time-varying or interactive quantity not as a mutable variable, but rather as an immutable stream of values, one for each time quanta. The trick then is that while each value is a represented by a potentially infinite stream of values, the streams are lazily calculated (so that memory isn't taken up until needed), and stream values aren't looked at for time quanta in the past (so that the previous calculations may be garbage collected). The calculation is nicely functional and immutable, but the part of the calculation you are "looking at" changes with time.
This is all rather intricate, and combining streams like this is tricky, particularly if you wish to avoid memory leaks and have everything work in a thread-safe and efficient manner. There are a few Scala libraries that implement Functional Reactive Programming, but maturity isn't yet very high. The most interesting is probably scala.react, described here .
Games are often high-performance affairs, in which case you may find that mutable state is just the thing you need.
However, in this case, there are a couple of simple solutions:
case class MovingTexture(position: VecXY, velocity: VecXY) extends Renders with Advances {
def advance(ms: Float) = copy(position = position + ms*velocity
def accelerate(acc: Float, ms: Float) = copy(velocity = velocity + ms*acc)
...
}
That is, instead of having your classes update themselves, have them return new copies of themselves. (You can see how this could get expensive quickly. For Tetris, no big deal. For Crysis? Maybe not so smart.) This seems like it just pushes the problem back one level: now you need a var for the MovingTexture, right? Not at all:
Iterator.iterate(MovingTexture(home, defaultSpeed))(_.advance(defaultStep))
This will produce an endless stream of position updates in the same direction. You can do more complicated things to mix in user input or whatnot.
Alternatively, you can
class Origin extends Renders {
// All sorts of expensive stuff goes here
}
class Transposed(val ori: Origin, val position: VecXY) extends Renders with Advances {
// Wrap TextureAtOrigin with inexpensive methods to make it act like it's moved
def moving(vel: VecXY, ms: Float) = {
Iterator.iterate(this).(tt => new Transposed(tt.ori, position+ms*vel))
}
}
That is, have heavyweight things never be updated and have lighter-weight views of them that make them look as though they've changed in the way that you want them changed.
There's a brochure called "How to design worlds" (by the authors of "How to design programs") which goes into some length about a purely functional approach to programming interactive applications.
Basically, they introduce a "world" (a datatype that contains all the game state), and some functions, such as "tick" (of type world -> world) and "onkeypress" (of type key * world -> world). A "render" function then takes a world and returns a scene, which is then passed to the "real" renderer.
Here's a sample of some code I've been working on that uses the approach of returning a copy rather than mutating state directly. The nice thing about this kind of approach, on the server side at least, is that it enables me to easily implement transaction-type semantics. If something goes wrong while doing an update, it's trivial for me to still have everything that was updated in a consistent state.
The code below is from a game server I'm working on, which does something similar to what you're doing, it's for tracking objects that are moving around in time slices. This approach isn't as spectacular as what Dave Griffith suggests, but it may be of some use to you for contemplation.
case class PosController(
pos: Vector3 = Vector3.zero,
maxSpeed: Int = 90,
velocity: Vector3 = Vector3.zero,
target: Vector3 = Vector3.zero
) {
def moving = !velocity.isZero
def update(elapsed: Double) = {
if (!moving)
this
else {
val proposedMove = velocity * elapsed
// If we're about to overshoot, then stop at the exact position.
if (proposedMove.mag2 > pos.dist2(target))
copy(velocity = Vector3.zero, pos = target)
else
copy(pos = pos + proposedMove)
}
}
def setTarget(p: Vector3) = {
if (p == pos)
this
else {
// For now, go immediately to max velocity in the correct direction.
val direction = (p - pos).norm
val newVel = direction * maxSpeed
copy(velocity = direction * maxSpeed, target = p)
}
}
def setTargetRange(p: Vector3, range: Double) = {
val delta = p - pos
// Already in range?
if (delta.mag2 < range * range)
this
else {
// We're not in range. Select a spot on a line between them and us, at max range.
val d = delta.norm * range
setTarget(p - d)
}
}
def eta = if (!moving) 0.0 else pos.dist(target) / maxSpeed
}
One nice thing about case classes in Scala is that they create the copy() method for you-- you just pass in which parameters have changed, and the others retain the same value. You can code this by hand if you're not using case classes, but you need to remember to update the copy method whenever you change what values are present in the class.
Regarding resources, what really made a difference for me was spending some time doing things in Erlang, where there is basically no choice but to use immutable state. I have two Erlang books I worked through and studied every example carefully. That, plus forcing myself to get some things done in Erlang made me a lot more comfortable with working with immutable data.
This series of short articles helped me as a beginner, in thinking Functionally in solving programming problems. The game is Retro (Pac Man), but the programmer is not.
http://prog21.dadgum.com/23.html