This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
F# getting a list of random numbers
I'm getting random value from list each time on tick (timer) but I'm getting the same 3 times only then it changes...
the code:
let timer = new DispatcherTimer()
timer.Tick.Add <| fun _ -> X.Change()
timer.Interval <- new TimeSpan(0,0,3)
member X.Change() =
(Seq.nth
(System.Random().Next(Seq.length actions))
<| actions)()
Why? I want to get different value each time
I'm not entirely sure about your example, but the general guideline is that you should create one instance of System.Random (or one instance per thread, if you have a multi-threaded application) and then use it multiple times.
Try something like this:
let timer = new DispatcherTimer()
let rnd = new System.Random()
timer.Tick.Add <| fun _ -> X.Change()
timer.Interval <- new TimeSpan(0,0,3)
member X.Change() =
(Seq.nth
(rnd.Next(Seq.length actions))
<| actions)()
The Random object is mutable and keeps some state that is used to generate the sequence of random values. When you create a new instance, it initializes the state using current time, so if you create multiple instances at the same time, you'll get the same numbers.
As an aside, if you need to access random elements of actions, then it would be better to store them as an array, because then you can just write:
member X.Change() =
actions.[rnd.Next(actions.Length)]()
Related
I'm relatively new to Z3 and experimenting with it in python. I've coded a program which returns the order in which different actions is performed, represented with a number. Z3 returns an integer representing the second the action starts.
Now I want to look at the model and see if there is an instance of time where nothing happens. To do this I made a list with only 0's and I want to change the index at the times where each action is being executed, to 1. For instance, if an action start at the 5th second and takes 8 seconds to be executed, the index 5 to 12 would be set to 1. Doing this with all the actions and then look for 0's in the list would hopefully give me the instances where nothing happens.
The problem is: I would like to write something like this for coding the problem
list_for_check = [0]*total_time
m = s.model()
for action in actions:
for index in range(m.evaluate(action.number) , m.evaluate(action.number) + action.time_it_takes):
list_for_check[index] = 1
But I get the error:
'IntNumRef' object cannot be interpreted as an integer
I've understood that Z3 isn't returning normal ints or bools in their models, but writing
if m.evaluate(action.boolean):
works, so I'm assuming the if is overwritten in a way, but this doesn't seem to be the case with range. So my question is: Is there a way to use range with Z3 ints? Or is there another way to do this?
The problem might also be that action.time_it_takes is an integer and adding a Z3int with a "normal" int doesn't work. (Done in the second part of the range).
I've also tried using int(m.evaluate(action.number)), but it doesn't work.
Thanks in advance :)
When you call evaluate it returns an IntNumRef, which is an internal z3 representation of an integer number inside z3. You need to call as_long() method of it to convert it to a Python number. Here's an example:
from z3 import *
s = Solver()
a = Int('a')
s.add(a > 4);
s.add(a < 7);
if s.check() == sat:
m = s.model()
print("a is %s" % m.evaluate(a))
print("Iterating from a to a+5:")
av = m.evaluate(a).as_long()
for index in range(av, av + 5):
print(index)
When I run this, I get:
a is 5
Iterating from a to a+5:
5
6
7
8
9
which is exactly what you're trying to achieve.
The method as_long() is defined here. Note that there are similar conversion functions from bit-vectors and rationals as well. You can search the z3py api using the interface at: https://z3prover.github.io/api/html/namespacez3py.html
I have read almost every definition of immutable/mutable variables on the internet but as a beginner I just do not grasp it fully so I was wondering if someone could really explain it in layman terms.
Immutable variables (or objects) in any programming language is what I understand when you cannot change the value of that variable after it has been assigned a value. For example, I am using the Haskell programming language, and I write:
let x = 5
Since Haskell has immutable variables, x can never have any other value than 5. So if I after that line of code write:
x = 2
I have in fact not changed the value of x but made a new variable with the same name, which will now be the one that is referenced when I call x, so after both lines of code I can only reach an x with the value of 2.
But what is a mutable variable then, and what programming languages have it? This is where it gets foggy for me. Because when people say mutable variable, they are obviously referring to a variable or object which value you can indeed change after it has been assigned an initial value.
Does this mean that if you have a mutable variable you actually manipulate that place in the computers memory for that variable, and in case of immutable variable you cannot manipulate that place in the computers memory or what?
I don't know how to explain my question any further, as I said, I understand that mutable = can change value of variable after initial value assignment, immutable = cannot. I get the definition. But I don't understand what it actually means in terms of what is going on "behind the scenes". I guess I am looking for easy examples on actual mutable variables.
This has nothing to do with immutability
let x = 5
x = 2
This is reassignment and definitely not allowed in Haskell
First let's look at a regular let assignment
Prelude> let x = 5 in x
5
it :: Num a => a
You can bind x using let, and rebind a new x in a nested let – this effectively shadows the outer x
Prelude> let x = 5 in let x = 2 in x
2
it :: Num a => a
Remember a let is basically a lambda
Prelude> (\x -> x) 5
5
it :: Num a => a
And of course a lambda can return a lambda; illustrates shadowing agian
Prelude> (\x -> (\x -> x)) 5 2
2
it :: Num a => a
I believe a shorthand answer to your question would be that a Mutable variable that holds a value that you would later want to be adjusted.
Depending on the language you're using is its method.
In Kotlin val and var are used to declare variables.
val is a constant while var is adjustable.
Mutable respectively immutable does not concern the variables but the values. Note: one also says the type is (im-)mutable.
For instance if the value is of an immutable type StudentCard, with fields ID and Name, then after creation the fields no longer can be changed. On a name change the student card must be reissued, a new StudentCard must be created.
A more elementary immutable type is String in java. Assigning the same value to two variables is no problem as one variable may not change the shared value. Sharing a mutable value could be dangerous.
A commont mutable type is the array in java and others. Sharing an array, say storing an array parameter in a field, risks that somewhere else the array content is changed inadvertently changing your field.
I have an array filled with objects, each object has an attribute named amount. I want to subtract a given number evenly from random objects based on the amount.
I'll better explain it on the following example:
Dim subtractBy as integer = 5 'means i want to substract a total of 5
Dim Generator As System.Random = New System.Random()
While (subtractBy > 0)
Dim randomItem = array2(Generator.Next(0, array2.Count))
If (randomItem.amount > 0 ) Then
randomItem.changeAmountBy(-1)
subtractBy = subtractBy - 1
End If
End While
The problem with that example is, every object has the same chance to be choosen for substraction. I want that every object gets higher chances linear to the amount atribute. So an object with amount=6 has 6x higher chance to be selected than the object with amount=1 and so on.
(Althought the example is in VB, I appreciate also general non-code answers)
Thank you
For fun, I am trying to write a simple simulation of the
Monty Hall problem
problem using F#.
I have created a function getShow which returns an array of three booleans (representing doors), one of which is randomly true (it has a car behind it) and the other two false.
let getShow =
let doorWithCar = System.Random().Next(3)+1
[|for door in 1..3 -> door = doorWithCar|]
Now when I try to get a sequence of shows using yield to call the getShow function, I keep getting the first random show repeated (I am guessing because of the way closures work in F#).
let shows =
seq { for i in 1 .. 10 do yield getShow} // Keeps generating the same show over and over
What is the correct way to call the getShow function using yield so that it actually calls the function and gets a new random array?
getShow is a value and not a function, so it's calculated once and you keep yielding the same value. To turn it into a function you have to add (). Also, you keep creating a new Random instance, which is probably initialized with the same time seed, not giving you what you want. Try this instead:
let random = System.Random()
let getShow() =
let doorWithCar = random.Next(3)+1
[|for door in 1..3 -> door = doorWithCar|]
let shows =
seq { for i in 1 .. 10 do yield getShow()}
I'm trying to make a function that defines a vector that varies based on the function's input, and set! works great for this in Scheme. Is there a functional equivalent for this in OCaml?
I agree with sepp2k that you should expand your question, and give more detailed examples.
Maybe what you need are references.
As a rough approximation, you can see them as variables to which you can assign:
let a = ref 5;;
!a;; (* This evaluates to 5 *)
a := 42;;
!a;; (* This evaluates to 42 *)
Here is a more detailed explanation from http://caml.inria.fr/pub/docs/u3-ocaml/ocaml-core.html:
The language we have described so far is purely functional. That is, several evaluations of the same expression will always produce the same answer. This prevents, for instance, the implementation of a counter whose interface is a single function next : unit -> int that increments the counter and returns its new value. Repeated invocation of this function should return a sequence of consecutive integers — a different answer each time.
Indeed, the counter needs to memorize its state in some particular location, with read/write accesses, but before all, some information must be shared between two calls to next. The solution is to use mutable storage and interact with the store by so-called side effects.
In OCaml, the counter could be defined as follows:
let new_count =
let r = ref 0 in
let next () = r := !r+1; !r in
next;;
Another, maybe more concrete, example of mutable storage is a bank account. In OCaml, record fields can be declared mutable, so that new values can be assigned to them later. Hence, a bank account could be a two-field record, its number, and its balance, where the balance is mutable.
type account = { number : int; mutable balance : float }
let retrieve account requested =
let s = min account.balance requested in
account.balance <- account.balance -. s; s;;
In fact, in OCaml, references are not primitive: they are special cases of mutable records. For instance, one could define:
type 'a ref = { mutable content : 'a }
let ref x = { content = x }
let deref r = r.content
let assign r x = r.content <- x; x
set! in Scheme assigns to a variable. You cannot assign to a variable in OCaml, at all. (So "variables" are not really "variable".) So there is no equivalent.
But OCaml is not a pure functional language. It has mutable data structures. The following things can be assigned to:
Array elements
String elements
Mutable fields of records
Mutable fields of objects
In these situations, the <- syntax is used for assignment.
The ref type mentioned by #jrouquie is a simple, built-in mutable record type that acts as a mutable container of one thing. OCaml also provides ! and := operators for working with refs.