I want to overwrite some elements of a vector x with a scalar a based on a 0/1 vector cond. In pseudocode: x[cond]=a.
x[cond] is not the right way of subsetting in Mata. I should use select(x,cond). Unfortunately, this latter object cannot be assigned to.
x[selectindex(cond)] = a fails because such an assignment requires the same dimensions on both sides of the =.
I could modify the latter approach to
x[selectindex(cond)] = J(sum(cond),1,a)
Is that the idiom in Mata? I was expecting something more straightforward because Stata has nice replace x = a if cond syntax.
In the general case, I think that's about as good as you're going to get. sum(cond) is safe if cond is 0 or 1, but a more general alternative is:
select = selectindex(cond)
x[select] = J(length(select), 1, a)
I agree that this is not the simplest syntax. An additional assignment colon operator := would be nice here.
If x and cond are views, st_store() is another option:
st_store(., st_viewvars(x), st_viewvars(cond), J(sum(cond), 1, a))
If you already know the variable names/indices and don't have to call st_viewvars(), all the better.
Related
I can't find anything about this through Google so I have to ask here. I want to do something like this (very pseudo code):
y = first_value
x={op_1 = >, op_2 = <, c = some_value}
if first_value x.op_1 x.c then
...
end
What that code says to me is that if first_value if greater than x's c value then do something. Now, I know I could set op_1 and op_2 to some value to differentiate between them and then compare values using separate if statements, but I would like to minimize the number of if statements used.
I was just wondering if something like this is possible, maybe even in a different form. Thanks in advance!
Not this way, an operator is a specific symbol that is part of the syntax. However, you can represent an operation using a function:
y = first_value
x={op_1 = function(a,b)return a>b end, op_2 = function(a,b)return a<b end, c = some_value}
if x.op1(first_value, x.c) then
...
end
Simple example: I have some functions and I need to call them all, to modify a structure, only in one function. With these simple functions the task can be made in ways that don't use void, but in others tasks you have to use void. So what can you do?
type player = { mutable name : string; mutable points : int } ;;
let putname brad = match brad with
{ name = x; points = y } -> { name = brad; points = y } ;;
let putpoint guy score = match guy with
{ name = x; points = y } -> { name = x; points = score } ;;
let loosers listplayer guy = guy :: listplayer ;;
Here is the problem - How can I do the next function?
let someoneloses guy = void
guy = putpoint guy 0 ;;
listplayer = loosers (listplayer guy) ;;
Given you are using the name "void" I'm assuming you are more familiar with C (or C++). In OCaml the equivalent of "void" (the name of the type for no value) is "unit". There is another difference though: while in C the syntax is complex enough that it have constructs for no values (for instance, you can either "return a_value;" or "return;", two differents yet syntactically valid use cases for the keyword "return"), in OCaml the syntax is simpler and always require a value. So we have a notation for "nothing", which is, astutely but maybe also confusedly, is written "()".
So, the OCaml equivalent of the C:
void do_nothing(void) { return; }
is written:
let do_nothing () = ()
(notice how OCaml syntax is simpler and easier to grok once you got the "()" trick).
Now that this is hopefully clearer, back to your question.
A function that returns nothing is a function that return "()", either explicitly (as "do_nothing" above) or because it ends with an expression that has "()" as its value. For instance, an assignment (something tell me you'll love assignments), such as:
let putpoint guy score = guy.points <- score
Now back to your problem. You seem to be doing some kind of game with players represented as mutable records and some functions modifying those records as the game develop. You need not use pattern matching for that. Actually, functions such as "putpoint" above is probably what you want. But then you need some more state in your program: the list of loosers for instance is probably going to be a reference to a list that you modify etc.
This is the "imperative" side of OCaml but there is another one, which is usually regarded as more elegant although often slower in general (but not in functional languages which are optimised for this technique), consisting of refraining from altering state (changing values of things) but instead using functions merely taking values and returning values. Implemented like this, a player would be represented as an immutable record and each function acting a user would take an "old user" and return a "new user", and the same goes with the list of loosers, and so on. Actually, the whole game state would be represented as a big value that the "main loop" of your program would, given the previous value, and possible also the time and user inputs, would compute the "new state" and return it.
Have fun!
Also, your question has nothing to do with ocaml-batteries.
since you are using mutable data, you just have to assigned the value directly.
let p = {name = "me";points=0};;
let update x = x.name <- "you";
x.points <- 3;;
update p ;;
I am trying to find if x's first bit from right is 1, so I check if the value of x^1 is 1. However,
int x=6;
if (x^1!=1)
gives wrong answer, but
if (int(x^1)!=1)
gives the correct answer.
I am not sure why. Could someone clarify this for me?
It's a trap of operator precedence. Operator precedence determines how operations are "grouped" (like how 2*3+4 results in the 2*3 being "grouped" together). Adding parentheses changes how things are "grouped" (for example, 2*(3+4) causes 3+4 to be "grouped" together).
x^1!=1 is equivalent to x^(1!=1), which can be simplified to x^0.
int(x^1)!=1 is equivalent to (x^1)!=1 (because you've manually added parentheses here; the int part isn't very relevant; it's the parentheses that are important).
As you can see, x^(1!=1) and (x^1)!=1 are not the same.
If your goal is to check the first bit, I might suggest using a bitwise-AND (&). You can then just do if (x & 1) (but beware, mixing & and == will result in the same issues as you were having before, so use parentheses if you want to write if ((x & 1) == 1)).
Simply, != (Not equal relational operator) has high precedence than ^ (XOR bitwise operator). Check precedence
int x=6;
case 1: if (x^1!=1)
First, 1!=1 is 0; then 6^0= 6. (110 ^ 000 = 110); Check XOR table
Case 2: if (int (x^1)!=1)
First, x^1= 7; then 7!=1 is 1 (true).
#Cornstalks is right with his answer.
I just had that in mind ( it does'nt in fact answer your problem , but can make it more readable) :
Another approach for solving this problem is simply using the modulo operator:
if(x%2 == 0) // then first bit is 0
else // first bit is 1
In the end your task is simply a check for even or odd values.
I would like to perform the following:
if(x == true)
{
// do this on behalf of x
// do this on behalf of x
// do this on behalf of x
}
Using a conditional operator, is this correct?
x == true ? { /*do a*/, /*do b*/, /*do c*/ } : y == true ? ... ;
Is this malformed?
I am not nesting more than one level with a conditional operator.
The expressions I intend to use are highly terse and simple making a conditional operator, in my opinion, worth using.
P.S. I am not asking A. Which I should use? B. Which is better C. Which is more appropriate
P.S. I am asking how to convert an if-else statement to a ternary conditional operator.
Any advice given on this question regarding coding standards etc. are simply undesired.
Don't compare booleans to true and false. There's no point because they're true or false already! Just write
if (x)
{
// do this on behalf of x
// do this on behalf of x
// do this on behalf of x
}
Your second example doesn't compile because you use { and }. But this might
x ? ( /*do a*/, /*do b*/, /*do c*/ ) : y ? ... ;
but it does depend on what /*do a*/ etc are.
Using comma operator to string different expressions together is within the rules of the language, but it makes the code harder to read (because you have to spot the comma, which isn't always easy, especially if the expression isn't really simple.
The other factor is of course that you can ONLY do this for if (x) ... else if(y) ... type conditionals state.
Sometimes, it seems like people prefer "short code" from "readable code", which is of course great if you are in a competition of "who can write this in the fewest lines", but for everything else, particularly code that "on show" or shared with colleagues that also need to understand it - once a software project gets sufficiently large, it usually becomes hard to understand how the code works WITHOUT obfuscation that makes the code harder to read. I don't really see any benefit in using conditional statements in the way your second example described. It is possible that the example is bad, but generally, I'd say "don't do that".
Of course it works (with C++11). I have not tried a solution but following Herb Sutters way you can use ether a function call or a lambda which is immediately executed:
cond ?
[&]{
int i = some_default_value;
if(someConditionIstrue)
{
Do some operations ancalculate the value of i;
i = some calculated value;
}
return i;
} ()
:
somefun() ;
I have not tried to compile it but here you have an result whih is either computed with an lambda or an normal function.
I am using th z3 C++ API. if I create this simple false expression:
z3::expr x = C->int_const("x");
z3::expr p = z3::forall(x, x==0);
and try to solve, I get an unknown outcome. I am not an expert of strategies and tactics, but I am sure that z3 can solve this, if I use the right tactic.
I also tried
z3::expr p = !z3::forall(x, x==0);
with, of course, the same runknown esult.
I'm not familiar with z3, but from a general C++ perspective, wouldn't x==0 evaluate first, i.e. wouldn't your call be equivalent to implies(x, 1)? From a quick search it seems you may have to construct each piece of the statement as a z3 object, for example:
Z3_ast consequent = Z3_mk_eq(ctx, x, 0);
Z3_ast theorem = Z3_mk_implies(ctx, x, consequent);
But the above is not correct, either. I believe the parameters x and 0 themselves have to be instances of Z3_ast that encapsulate the statement you mean (as opposed to their interpolated values or references).