Does golang have the equivalent of this Python short circuit idiom `z = x or y` - go

In Python z = x or y can be understood as assign z as if x is falsey, then y, else x, is there a similar idiom in golang?
Specifically the two variables on the right are strings, I'd like to assign the first if it's non-emtpy, otherwise the second.

No, you have to use if/else:
s1, s2 := "", "hello"
var x string
if s1 == "" {
x = s2
} else {
x = s1
}

Related

Different expressions for different outputs in Halide

I'm new to Halide so also kinda didn't know how to ask the question. Let me explain. Let's assume I have a simple code for Halide's generator like this:
class Blur : public Generator<Blur>{
public:
Input<Buffer<float>> in_func{"in_func", 2};
Output<Buffer<float>> forward{"forward", 2};
Var x, y, n;
void generate(){
Expr m1 = in_func(x+1, y+2)+in_func(x+2, y+1);
Expr m2 = in_func(x+1, y+2)-in_func(x+2, y+1);
Expr m3 = in_func(x+2, y+1)+in_func(x+1, y+1);
Expr m4 = in_func(x+2, y+1)-in_func(x+1, y+1);
Expr w0010_2 = -in_func(x+2, y+2)+in_func(x, y+2);
Expr w0111_2 = -in_func(x+3, y+2)+in_func(x+1, y+2);
forward(0,0) = w0010_2+m4+m3+m2+m1;
forward(1,0) = -w0111_2+m4+m3-m2-m1;
forward(0,1) = w0010_2-m4+m3-m2+m1;
forward(1,1) = w0111_2-m4+m3+m2-m1;
}
};
What I want to achieve is to define that output at index (0,0) should be the result of m1 + m2 but output at index (1,0) should be the result of different expression, for example, m1 - m2. I would be really grateful for help.
What I want to achieve is to define that output at index (0,0) should be the result of m1 + m2 but output at index (1,0) should be the result of different expression, for example, m1 - m2. [...] I want result[0][0] = expression1, result[0][1] = expression2, result[1][0] = expression3 and result[1][1] = expression4. But also result[0][2], result[0][4] and so on = expression1
Compute the values x%2 and y%2 and use their values in a select:
forward(x, y) = select(
x % 2 == 0 && y % 2 == 0, m1 + m2,
x % 2 == 1 && y % 2 == 0, m1 - m2,
x % 2 == 0 && y % 2 == 1, expr3,
/* otherwise, */ expr4
);
Select is a pure if-then-else. It evaluates all of its arguments and then picks the one corresponding to the first true predicate. If the expressions all use nearby points of in_func, this might not be too slow.
If you find that performance suffers, I'd try to create four funcs, one for each of the four expressions, and then select loads from those. If that's still too slow, you might be able to optimize the indexing to not compute any extra points. If you show all four expressions, I might be able to help you do that.

Is there a more elegant Go implementation of Newton's method?

I'm doing the Go tutorials and am wondering whether there is a more elegant way to compute a square root using Newton's method on Exercise: Loops and Functions than this:
func Sqrt(x float64) float64 {
count := 0
var old_z, z float64 = 0, 1
for ; math.Abs(z-old_z) > .001; count++ {
old_z, z = z, z - (z*z - x) / 2*z
}
fmt.Printf("Ran %v iterations\n", count)
return z
}
(Part of the specification is to provide the number of iterations.) Here is the full program, including package statement, imports, and main.
First, you algorithm is not correct. The formula is:
You modelled this with:
z - (z*z - x) / 2*z
But it should be:
z - (z*z - x)/2/z
Or
z - (z*z - x)/(2*z)
(Your incorrect formula had to run like half a million iterations even to just get as close as 0.001! The correct formula uses like 4 iterations to get as close as 1e-6 in case of x = 2.)
Next, initial value of z=1 is not the best for a random number (it might work well for a small number like 2). You can kick off with z = x / 2 which is a very simple initial value and takes you closer to the result with fewer steps.
Further options which do not necessarily make it more readable or elegant, it's subjective:
You can name the result to z so the return statement can be "bare". Also you can create a loop variable to count the iterations if you move the current "exit" condition into the loop which if met you print the iterations count and can simply return. You can also move the calculation to the initialization part of the if:
func Sqrt(x float64) (z float64) {
z = x / 2
for i, old := 1, 0.0; ; i++ {
if old, z = z, z-(z*z-x)/2/z; math.Abs(old-z) < 1e-5 {
fmt.Printf("Ran %v iterations\n", i)
return
}
}
}
You can also move the z = x / 2 to the initialization part of the for but then you can't have named result (else a local variant of z would be created which would shadow the named return value):
func Sqrt(x float64) float64 {
for i, z, old := 1, x/2, 0.0; ; i++ {
if old, z = z, z-(z*z-x)/2/z; math.Abs(old-z) < 1e-5 {
fmt.Printf("Ran %v iterations\n", i)
return z
}
}
}
Note: I started my iteration counter with 1 because the "exit" condition in my case is inside the for and is not the condition of for.
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) float64 {
z := 1.0
// First guess
z -= (z*z - x) / (2*z)
// Iterate until change is very small
for zNew, delta := z, z; delta > 0.00000001; z = zNew {
zNew -= (zNew * zNew - x) / (2 * zNew)
delta = z - zNew
}
return z
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(math.Sqrt(2))
}

Swapping two numbers using only two variables

How is it performing swapping?
a=a+b
b=a+b
a=b+a
I don't agree that it's swap to a book!!!
The book options include "complements of values of a and b" ,"negate and b".Hope these options aren't satisfying it too???
The correct algorithm should be:
a = a + b
b = a - b
a = a - b
The swap is performed using XOR, which is typically written as a plus within a circle; for example:
a := 5
b := 7
a := a xor b (2)
b := a xor b (5)
a := b xor a (7)
I recently underwent an interview for java fresher, the interviewer asked me to perform swapping of two numbers (but in one line).
Swapping of two numbers can be performed in one line also, without using a temp variable.
The logic is really simple,
x is added with y in the same line, y is assigned as x which is subtracted by their sum.
after performing this one line arithmetics the numbers were swapped. (only in one line)
public class SwapInOneLine {
public static void main(String[] args) {
int x = 10; int y = 20;
System.out.println("Before Swaping: x = " + x + " and y= " + y);
x = x + y - (y = x);
System.out.println("After Swaping: x = " + x + " and y= " + y);
}}
output:
Before Swaping: x = 10 and y= 20
After Swaping: x = 20 and y= 10
We can use XOR (^) for this.
Advantage of XOR : As XOR works on bit level, it takes very less amount of time than any other operations.
If a = 5 and b = 7
then to swap :
a = a ^ b
b = a ^ b
a = a ^ b
Where '^' means XOR.
Result :
a = 7 and b = 5
Actually, it can be done by two ways:
int a = 5, b = 10;
Using Addition(+) and Subtraction(-)
a = a + b;
b = a - b;
a = a - b;
Using Multiple(*) and Division(/)
a = a * b;
b = a / b;
a = a / b;

Is {true} x := y { x = y } a valid Hoare triple?

I am not sure that
{ true } x := y { x = y }
is a valid Hoare triple.
I am not sure one is allowed to reference a variable (in this case, y), without explicitly defining it first either in the triple program body or in the pre-condition.
{ y=1 } x := y { x = y } //valid
{true} y := 1; x := y { x = y } //valid
How is it?
I am not sure that
{ true } x := y { x = y }
is a valid Hoare triple.
The triple should be read as follows:
"Regardless of starting state, after executing x:=y x equals y."
and it does hold. The formal argument for why it holds is that
the weakest precondition of x := y given postcondition { x = y } is { y = y }, and
{ true } implies { y = y }.
However, I completely understand why you feel uneasy about this triple, and you're worried for a good reason!
The triple is badly formulated because the pre- and post condition do not provide a useful specification. Why? Because (as you've discovered) x := 0; y := 0 also satisfies the spec, since x = y holds after execution.
Clearly, x := 0; y := 0 is not a very useful implementation and the reason why it still satisfies the specification, is (according to me) due to a specification bug.
How to fix this:
The "correct" way of expressing the specification is to make sure the specification is self contained by using some meta variables that the program can't possible access (x₀ and y₀ in this case):
{ x=x₀ ∧ y=y₀ } x := y { x=y₀ ∧ y=y₀ }
Here x := 0; y := 0 no longer satisfies the post condition.
{ true } x := y { x = y } is a valid Hoare triple. The reason is as follows:
x := y is an assignment, therefore, replace that in the precondition.
The precondition stands as {y=y}, which implies {true}.
In other words, {y=y} => {true}.
* If x:=y, then Q. Q.E.D. _*

Can I avoid "rightward drift" in Haskell?

When I use an imperative language I often write code like
foo (x) {
if (x < 0) return True;
y = getForX(x);
if (y < 0) return True;
return x < y;
}
That is, I check conditions off one by one, breaking out of the block as soon
as possible.
I like this because it keeps the code "flat" and obeys the principle of "end
weight". I consider it to be more readable.
But in Haskell I would have written that as
foo x = do
if x < 0
then return x
else do
y <- getForX x
if y < 0
then return True
else return $ x < y
Which I don't like as much. I could use a monad that allows breaking out, but
since I'm already using a monad I'd have to lift everything, which adds words
I'd like to avoid if I can.
I suppose there's not really a perfect solution to this but does anyone have
any advice?
For your specific question: How about dangling do notation and the usage of logic?
foo x = do
if x < 0 then return x else do
y <- getForX x
return $ y < 0 || x < y
Edit
Combined with what hammar said, you can even get more beautiful code:
foo x | x < 0 = return x
| otherwise = do y <- getForX x
return $ y < 0 || x < y
Using patterns and guards can help a lot:
foo x | x < 0 = return x
foo x = do
y <- getForX x
if y < 0
then return True
else return $ x < y
You can also introduce small helper functions in a where clause. That tends to help readability as well.
foo x | x < 0 = return x
foo x = do
y <- getForX x
return $ bar y
where
bar y | y < 0 = True
| otherwise = x < y
(Or if the code really is as simple as this example, use logic as FUZxxl suggested).
The best way to do this is using guards, but then you need to have the y value first in order to use it in the guard. That needs to be gotten from getForX wich might be tucked away into some monad that you cannot get the value out from except through getForX (for example the IO monad) and then you have to lift the pure function that uses guards into that monad. One way of doing this is by using liftM.
foo x = liftM go (getForX x)
where
go y | x < 0 = True
| y < 0 = True
| otherwise = x < y
Isn't it just
foo x = x < y || y < 0 where y = getForX x
EDIT: As Owen pointed out - getForX is monadic so my code above would not work. The below version probably should:
foo x = do
y <- getForX x
return (x < y || y < 0)

Resources