Syntax or construct to simplify if() statement? - syntax

I'm looking for a semantic or language construct that will simplify some of my if statements. If I have an if statement with an or, where I 'choose' between two values, I'd like to have that chosen variable available later on in the code.
I'll write this in pseudo-code:
if ( x or y ) {
function(z);
}
Where z is the value of x or y, whichever triggered the if to be true. Otherwise I'm writing
if ( x ) {
...
function(x);
}
if ( y ) {
...
function(y);
}
Now in that example the duplication isn't much, but in my actual situation, there are about 6 lines of code that would be identical duplication within each if block. So I write something like:
if ( x ) {
z = x;
}
if ( y ) {
z = y;
}
if ( z ) {
...
function(z);
}
But that just seems so roundabout I suspect that somewhere along the line some guru came up with a nice syntax to make a one-line if. Is there a construct in a language anywhere where I can bind the triggering value into a variable in the subsequent block? What would this structure be called?
The actual situation I'm working in is in PHP, so I realize PHP may not have this capability.

In Python (also Ruby), the expression x or y evaluates to x if it is true, otherwise y. You could write the statement as f(x or y), or z = x or y.

For this exact situation. You can use the ? operator:
z = x ? x : y;
Which reads: z is (if x is not false) x otherwise it is y.

Actually, something like
if ( $z = ( $x ? $x : $y ) ) {
function($z);
}
Works as advertised in PHP. Thanks, slebetman!

Related

Understanding different types in Fortran

I was reading a Fortran code, came across the following code, couldn't understand what it does.
m%AllOuts( BAzimuth(k) ) = m%BEMT_u(indx)%psi(k)*R2D
I know that % here works like a pipe indicator to access values in a way similar to a dictionary in Python. I have a dictionary m let's say and the first key is AllOuts, but what does anything inside parentheses mean? Is it like another dictionary?
The percent sign is not denoting a dictionary. There are no native dictionaries in Fortran.
The percent sign denotes the component of a type. For example:
! Declare a type
type :: rectangle
integer :: x, y
character(len=8) :: color
end type rectangle
! Declare a variable of this type
type(rectangle) :: my_rect
! Use the type
my_rect % x = 4
my_rect % y = 3
my_rect % color = 'red'
print *, "Area: ", my_rect % x * my_rect % y
The parentheses could either indicate the index of an array, or the arguments of a call.
So, for example:
integer, dimension(10) :: a
a(8) = 16 ! write the number 16 to the 8th element of array a
Or, as a prodedure:
print *, my_pow(2, 3)
...
contains
function my_pow(a, b)
integer, intent(in) :: a, b
my_pow = a ** b
end function my_pow
In order to figure out what m is, you'd need to look at the declaration of m, which would be something like
type(sometype) :: m
or
class(sometype) :: m
Then you'd need to find out the type declaration, which would be something like
type :: sometype
! component declarations in here
end type
Now one of the components, BEMT_u, is almost certainly an array of a different type, which you'd also need to look up.

Nest let syntax from ocaml

I'm just starting to learn Rust and I'm coming from an OCaml background.
One thing that I often use is nested let expressions, in order to group related code together.
let x =
let y = 42 in
y + 1
in
...
My naive translation of this to rust would be:
let x =
let y = 42;
y + 1
;
However this fails to compile.
Is this type of syntax possible, or is it heavily frowned upon and thus is not supported?
Rust uses curly braces to delimit scopes. This works fine:
let x = {
let y = 42;
y + 1
};

How can I emulate the results of this if then then statement while using correct syntax?

Working on an exercise for university class and cant seem to represent what I am trying to do with correct syntax in ocaml. I want the function sum_positive to sum all the positive integers in the list into a single int value and return that value.
let int x = 0 in
let rec sum_positive (ls: int list) = function
|h::[] -> x (*sum of positive ints in list*)
|[] -> 0
|h::t -> if (h >= 0) then x + h then sum_positive t else sum_positive t (*trying to ensure that sum_positive t will still run after the addition of x + h*)
On compiling I am met with this error,
File "functions.ml", line 26, characters 34-38:
Error: Syntax error
This points to the then then statement I have in there, I know it cannot work but I cant think of any other representations that would.
You have if ... then ... then which is not syntactically valid.
It seems what you're asking is how to write what you have in mind in a way that is syntactically valid. But it's not clear what you have in mind.
You can evaluate two expressions in OCaml sequentially (one after the other) by separating them with ;. Possibly that is what you have in mind.
However it seems to me your code has bigger problems than just syntax. It appears you're trying to use x as an accumulated sum for the calculation. You should be aware that OCaml variables like x are immutable. Once you say let x = 0, the value can't be changed later. x will always be 0. The expression x + h doesn't change the value of x. It just evaluates to a new value.
The usual way to make this work is to pass x as a function parameter.
I was getting an issue that had involved the parameter of , I believe it was because I was trying to add an int value to function of type int list. This is what I ended up with.
let rec sum_positive = function
|[] -> 0
|h::t -> if h > 0 then h + (sum_positive t) else sum_positive t
a lot simpler than I thought it out to be.

Assigning values to multiple variables in Go

I recently came up across this:
func main() {
x, y := 0, 1
x, y = y, x+y
fmt.Println(y)
}
What I thought was that:
x, y = y, x+y
Is identical to:
x = y
y = x+y
Which would result to final values x = 1, y = 2
However the final values I get is x = 1, y = 1
Why is that?
Thanks.
This is how it's specified:
The assignment proceeds in two phases. First, the operands of index expressions and pointer indirections (including implicit pointer indirections in selectors) on the left and the expressions on the right are all evaluated in the usual order. Second, the assignments are carried out in left-to-right order.
Assignment first evaluates all expressions on the right side and then assigns the results to the variables on the left side.
Your
x, y = y, x+y
is basically equivalent to this
tmp1 := y
tmp2 := x+y
x = tmp1
y = tmp2
You can even use this fact to swap 2 variables in one line, like this:
a, b = b, a

"Ruby-esque" if else conditional statements

I'm currently reading The Ruby Programming Language, and I am not sure how to read Ruby-esque if else statements properly. Can you help me write the ruby code below in the second code block in regular if-else statements like this?
if some_condition
return x
else
return y
end
So the ruby codes I am unsure of are these.
minimum = if x < y then x else y end
max = x > y ? x : y
Thank you!
Both of the forms you seem to be having difficulty with make use of an idea Ruby takes from the Functional Programming paradigm: namely, Everything is an expression, and therefore returns a value. This is even true for conditional statements, an idea that languages like Java don't really support (for example:
public boolean test() {
boolean x = if (1 > 2 ) { false; } else { true; };
return x;
}
simply isn't syntactically valid).
You can see this in a Ruby terminal:
will_be_assigned_nil = false if (1 > 2) # => nil
will_be_assigned_nil # => nil
So, to your question.
The first one can be rewritten like this:
if x < y
mininum = x
else
minimum = y
end
The second is like the ternary operator in other languages, and is equivalent to:
if x > y
max = x
else
max = y
end
It's helpful to remember the roots & heritage of languages when trying to understand their constructs. Ruby shares the "More Than One Way To Do It" philosophy with Perl, and idiomatic Ruby code often has a high emphasis on elegance.
The "post-expression"-style conditionals are a good example of this. If I have guard expressions at the start of my methods, it's not uncommon for me to write:
raise "Pre-condition x not met" unless x # (or "if !x" , preference thing)
raise "Pre-condition y not met" unless y # etc., etc.
instead of
if !x
raise "Pre-condition x not met"
end
if !y
raise "Pre-condition y not met"
end

Resources