overloading ++ C# - operator-overloading

public static MyClass operator++(MyClass op)
{
MyClass result = new MyClass(); // MyClass() x=y=z=0;
result.x = op.x + 1;
result.y = op.y + 1;
result.z = op.z + 1;
return result:
}
//...
public void Main()
{
MyClass c = new MyClass();
MyClass b = new MyClass(1,2,3); //ctor x = 1, ...
c = b++;
}
The question is why variable b going to change?
because result.x = op.x + 1; shouldn't change op.x
result actually is c is (1,2,3) b is (2,3,4)
I don't understand why not c is (2,3,4) and b is (1,2,3)

You say, "because result.x = op.x + 1 shouldn't change op.x." But ++ is not the same as + 1. It is the standard postfix increment operator which increments the operand b by using your custom overload -- it assigns the new value to b immediately after passing the previous value to c. If it were the prefix operator (++b), it would have incremented before passing the value to c.
Without any overloads at all, the code:
b++
Is equivalent to:
b = b + 1
And
c = b++
Is equivalent to:
c = b;
b = b + 1;
Now using your overload, it's more equivalent to:
c = b;
b = call_your_++_overload(b);

Behaviour you are describing is according to the documentation:
postfix increment operation - The
result of the operation is the value
of the operand before it has been
incremented.
Both b++ (postfix operator) and ++b (prefix operator) changes original variable. To get desired results I would suggest overloading + operator and change c = b++; to c = b + 1;

Related

How to use string.split() without foreach()?

Write a program in Scala that reads an String from the keyboard and counts the number of characters, ignoring if its UpperCase or LowerCase
ex: Avocado
R: A = 2; v = 1; o = 2; c = 1; d = 2;
So, i tried to do it with two fors iterating over the string, and then a conditional to transform the character in the position (x) to Upper and compare with the character in the position (y) which is the same position... basically i'm transforming the same character so i can increment in the counter ex: Ava -> A = 2; v = 1;
But with this logic when i print the result it comes with:
ex: Avocado
R: A = 2; v = 1; o = 2; c = 1; a = 2; d = 1; o = 2;
its repeting the same character Upper or Lower in the result...
so my teacher asked us to resolve this using the split method and yield of Scala but i dunno how to use the split without forEach() that he doesnt allow us to use.
sorry for the bad english
object ex8 {
def main(args: Array[String]): Unit = {
println("Write a string")
var string = readLine()
var cont = 0
for (x <- 0 to string.length - 1) {
for (y <- 0 to string.length - 1) {
if (string.charAt(x).toUpper == string.charAt(y).toUpper)
cont += 1
}
print(string.charAt(x) + " = " + cont + "; ")
cont = 0
}
}
}
But with this logic when i print the result it comes with:
ex: Avocado
R: A = 2; V = 1; o = 2; c = 1; a = 2; d = 1; o = 2;
Scala 2.13 has added a very handy method to cover this sort of thing.
inputStr.groupMapReduce(_.toUpper)(_ => 1)(_+_)
.foreach{case (k,v) => println(s"$k = $v")}
//A = 2
//V = 1
//C = 1
//O = 2
//D = 1
It might be easier to group the individual elements of the String (i.e. a collection of Chars, made case-insensitive with toLower) to aggregate their corresponding size using groupBy/mapValues:
"Avocado".groupBy(_.toLower).mapValues(_.size)
// res1: scala.collection.immutable.Map[Char,Int] =
// Map(a -> 2, v -> 1, c -> 1, o -> 2, d -> 1)
Scala 2.11
Tried with classic word count approach of map => group => reduce
val exampleStr = "Avocado R"
exampleStr.
toLowerCase.
trim.
replaceAll(" +","").
toCharArray.map(x => (x,1)).groupBy(_._1).
map(x => (x._1,x._2.length))
Answer :
exampleStr: String = Avocado R
res3: scala.collection.immutable.Map[Char,Int] =
Map(a -> 2, v -> 1, c -> 1, r -> 1, o -> 2, d -> 1)

Where do I put a return in a function?

My code is returning 2 errors, both are unresolved identifiers. I looked up what means and most query answers are saying that I need to declare the constant first, but I have already done that.
I'm very new to coding and everytime I encountered this problem it was because I forgot to declare the constant or variable and I would catch my mistake but I'm stumped on this one.
var counter = 2
func fibonacci(_ x:Int ) -> Int {
var a = 1
var b = 1
if counter < x {
let sum = a + b
a = b
b = sum
counter += 1
}
print(sum)
return sum
}
fibonacci(5)
I bet you'll want to define counter within the scope of your function (passing it as a parameter might not make sense) and then define sum outside the scope of the if statement like this:
func fibonacci(_ x:Int ) -> Int {
var a = 1
var b = 1
var sum = 0
var counter = 0
if counter < x {
sum = a + b
a = b
b = sum
counter += 1
}
print(sum)
return sum
}
You've declared the variable sum inside the if condition and using it outside the if condition.
Return b instead of sum at the end of the function. Your if block will be executed only once. You should use while loop
var counter = 2
func fibonacci(_ x:Int ) -> Int {
var a = 1
var b = 1
while counter < x {
let sum = a + b
a = b
b = sum
counter += 1
}
print(b)
return b
}
print(fibonacci(5))
You can simplify the swapping using a tuple
var counter = 2
func fibonacci(_ x:Int ) -> Int {
var a = 1
var b = 1
while counter < x {
(a,b) = (b,a+b)
counter += 1
}
print(b)
return b
}
print(fibonacci(5))
var counter = 2
func fibonacci(_ x:Int ) -> Int {
var a = 1
var b = 1
var sum = 0 //this is when if you want to add sum
//var counter = 0 if you may please work around the counter
if counter < x {
sum = a + b
a = b
b = sum
counter += 1
}
return sum //if you declare sum then return sum could be used
}
var x = fibonacci(5)//here the return value is stored or used for further computations
print(x) // the returned value can be printed in this way or directly print(fibonacci(5))
If you feel like learning it more please go through following link https://docs.swift.org/swift-book/LanguageGuide/Functions.html
The code above is not a solution to fibonacci series but a solution to your error. Fibonacci series can be solved in many ways using logic. As your question is only for the errors the program above solves it. If you feel like studying it using algorithms please checkout this link: https://www.codewithc.com/fibonacci-series-algorithm-flowchart/
I hope the answer helps!
The unresolved indentifiers errors is because neither counter or sum are variables defined.
Just define them, Eg:
var sum = 0;
func fibonacci(counter: Int, x:Int) -> Int {
var a = 1
var b = 1
if counter < x {
sum = a + b;
a = b
b = sum
return fibonacci(counter: counter + 1, x: x)
}
return sum
}
fibonacci(counter: 0, x: 5)
Note: the fibonacci func is not working properly but the identified errors were solved.

how to modify self-defined scala operators' precedence

Is it possible to modify the precedence of any self-defined operators?
For example, I implement elementary arithmetic with totally self-defined operators.
case class Memory(name:String){
var num:Num = null
def <<=(x:Num): Unit = {
println(s"assign ${x.value}")
this.num = x
}
}
case class Num(var value:Int) {
def +|+(x:Num) = {
println("%d + %d = %d".format( value,x.value,x.value + value ))
Num(value + x.value)
}
def *|*(x:Num) = {
println("%d * %d = %d".format( value,x.value,x.value * value ))
Num(value * x.value)
}
}
val m1 = Memory("R")
val a = Num(1)
val b = Num(3)
val c = Num(9)
val d = Num(12)
m1 <<= a *|* b +|+ c +|+ d *|* a
println("final m1 ",m1.num.value)
The results are
1 * 3 = 3
3 + 9 = 12
12 * 1 = 12
12 + 12 = 24
assign 24
(final m1 ,24)
Apparently the precedence is correct. I want *|* be the same precedence as * and +|+ the same as +, <<= is equivalent as = as well. How scala figure it out?
Answering the question about modyfing operator precedence - to change it you basically just have to change the first character of your custom operator - this is how scala figures out precedense for infix operators, by just looking at the first character. So if you eg. add an operator *|+:
It will have same precedence as *|*, like with * and *.
"Bigger" precedence than +|+, just like with * and +.
Unfortunately there is no other way to deal with it right now. No custom annotations/weights and so on to avoid making reading code too fuzzy.
The precedence rules are very well summarized here - Operator precedence in Scala.
About your issue though - you get the right results.
*|*, as well as * are left-associative operators and their first character is *, so they have equal precedense.
Your operation:
a *|* b +|+ c +|+ d *|* a
Translates to
a * b + c + d * a, which is 1 * 3 + 9 + 12 * 1.
Applying standard precedence rules - (a*b) + c + (d*a) result is 24.

Kotlin: Curly braces around several expressions (or statements)

I think this question is somewhat related to Kotlin function declaration: equals sign before curly braces
In Scala, every statement is an expression (possibly with Unit type). If we surround multiple expressions with braces, then the final expression is the actual value of the curly braced part. Therefore,
// Scala
val a = {
val b = 1
val c = b + b
c + c
}
println(a)
The type of a is Int and the code prints the value 4.
However, in Kotlin, this is somewhat different.
If we do the same thing in the Kotlin,
// Kotlin
val a = {
val b = 1
val c = b + b
c + c
}
println(a)
The type of a is () -> Int and the code prints the Function0<java.lang.Integer>, which means a 0-ary function object with result type Int.
So if we want to print the value 4, we need to do println(a()).
In fact, the expression {} in Kotlin is a function () -> ().
I cannot find an explanation about this in Kotlin official reference pages. Without a parameter list or ->, curly braces make a function?
When I use Scala, I write many codes like the first code. However, in Kotlin, it creates a function object and we have to call the function, which may be an overhead in a loop or recursion.
Is there any document about this thing: just curly braces make a function object?
Any way to workaround the overhead in the second code if it is used many times?
EDIT
Here is the actual code that iterates many times:
in Java
while ((count = input.read(data, 0, BYTE_BLOCK_SIZE)) != -1) {
....
}
in Scala
while {
count = input.read(data, 0, BYTE_BLOCK_SIZE)
count != -1
} {
....
}
in Kotlin
while ({
count = input.read(data, 0, BYTE_BLOCK_SIZE)
count != -1
}()) {
...
}
You can see, only Kotlin makes a lot of function objects and calls them.
In Kotlin {} are always a lambda expression or a part of a syntax construct like while(true) {}. Probably different from Scala, but easy to grasp, nonetheless.
What you probably want is:
val a = run {
val b = 1
val c = b + b
c + c
}
println(a)
Kotlin has no build-in concept of "code blocks anywhere". Instead we use standard functions-helpers like run in the example above.
https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/run.html
If {} defines a function, you can just call the function upon declaring it, which will immediately evaluate it:
val a = {
val b = 1
val c = b + b
c + c
}()
println(a)
prints 4. (Note the () at the end of the block)
In Scala, every statement is an expression (possibly with Unit type)
That's not exactly true. Check: Is everything a function or expression or object in scala?
As Zoltan said {} defines functions so instead of:
// Kotlin
val a = {
val b = 1
val c = b + b
c + c
}
println(a)
it should be:
// Kotlin
val a = {
val b = 1
val c = b + b
c + c
}
println(a()) //you defined a function, which returns `4`, not expression
or
// Kotlin
val a = {
val b = 1
val c = b + b
c + c
}() //note these braces
println(a)
If you would like to print a value, not function, you can try to declare the variable and then use one of Kotlin functions to change a value like in example below:
var sum = 0
ints.filter { it > 0 }.forEach {
sum += it
}
print(sum)
Read: Higher-Order Functions and
Lambdas
Hope it will help

How to assign the same value to more var in scala

To instantiate the variables can do so:
scala> var (a, b, c) = (0, 0, 23)
a: Int = 0
b: Int = 0
c: Int = 23
but if I wanted to do such a thing?
scala> a = b = c
<console>:10: error: type mismatch;
found : Unit
required: Int
a = b = c
^
how can I do?
Thanks
var a,b,c = 0
should do the trick.
You can't do a = b = c because a has already been defined as a Int var, and with the a = b = c statement you are giving a a Unit, 'b = c'.
When you assign a value to a variable in Scala you don't get as a result the value assigned.
In other languages b = c would be evaluated to 23, the value of c. In Scala b = c is just a Unit, writing a = b = c is exactly like writing a = (b = c), hence the error.