How to use XOR in Kotlin - kotlin

I want to perform an XOR to find if one of two booleans a and b is true but not both. Searching for XOR in Kotlin gave me this answer
infix fun xor(other: Boolean): Boolean
Performs a logical xor operation between this Boolean and the other one. source
I'm still confused on how to implement this

It's an extension that can be invoked on any Boolean. You can use it like this:
true.xor(false)
or this:
true xor false
The last one works since the function is defined as infix.
Other similar extensions defined on Boolean are and, or and not:
//very useful example
true.not().or(true).and(false).xor(true)

find the single number in the array that every element has a duplicate except one.
var a = 0
for (i in numsArray){
a = a xor i
}
return a
eg. input = [2,2,1]
out = 1

Related

Is there a Kotlin std lib function to copy a list, removing all elements equal to ONE single element? A function taking only one non-collection arg?

Given a list of arbitrary objects
input = listOf(a, b, c, a)
... is there a function (with one non-collection argument) in the Kotlin standard library that I can use to make a copy of this list, removing all instances of ONE object?
Something like:
val filtered = input.removeAllInstancesOf(a)
To clarify, I'm aware of other (potential) solutions to this task:
Using the filter function to do this. → val output = input.filterNot { it == a }
Using the minus function with a collection → val output = input.minus(listOf(a))
Using the minus function with a non-collection argument → val output = input.minus(a) ← Only removes the first instance of a!
Removing all instances from a mutable list.
Writing such a function. → Wrap any of the above.
... but I'm wondering why I can't find a function which takes just ONE, non-collection value.
but I'm wondering why I can't find a function which takes just ONE, non-collection value.
Because that's a hyper-specific use-case of the already existing filter function. As you yourself showed it can be done in one line, and is probably the first thing a Kotlin dev would try to do (at least I would). So adding new function to the standard library probably doesn't add much value.

How can I use Mono<Boolean> as condition to call second method

I'm trying to make a call to one service after checking a condition from another service in an iterative way, like so:
if (productService.isProductNotExcluded(product)){
List<Properties> properties = propertiesService.getProductDetailProperties(product)
...
}
But since isProductExcluded is returning Mono<Boolean> I'm using this approach, which seems really odd:
Flux<Properties> properties = productService.isProductNotExcluded(productId)
.filter(notExcluded -> notExcluded)
.map(ok-> propertiesService.getProductDetailProperties(product))
...
Which is the correct way to deal with this kind of situation?
For a predicate which returns a Mono<Boolean>, you can also use filterWhen which takes a publisher as a predicate. Something like this:
Flux<Properties> properties = Mono.just(productId)
.filterWhen(prodId -> productService.isProductNotExcluded(prodId))
.map(validProductId -> propertiesService.getProductDetailProperties(validProductId));
What you are doing is not odd. I personally wouldn't return a boolean in a reactive function Mono<Boolean> if I can avoid it, but it's not wrong and sometimes you don't have a choice.
I personally would have an if/else statement in the map, for clarity. I would also change the name of the function, and rewrite the isNot part.
Flux<Properties> properties = productService.isExcluded(productId)
.flatMap(isExcluded -> {
if(!isExcluded)
return propertiesService.getProductDetailProperties(product);
else
return mono.empty();
});
This is matter of opinion and coding taste, but I find this to be a lot more readable, because you can read the code and understand it straight away. But this is a personal taste.
all() operator can be used.
According to the doc. all() Emits a single boolean true if all values of this sequence match
Mono all(Predicate<? super T> predicate) {}

Unexpected result when comparing CharSequence.reversed() return value

Have noticed a strange behavior when comparing a result of CharSequence.reversed() method.
val s = "a"
val subSequence = s.subSequence(0, 1)
println("$subSequence == ${subSequence.reversed()}: ${subSequence == subSequence.reversed()}")
Results in:
a == a: false
Moreover subSequence.reversed() == subSequence.reversed() is also false.
Can someone explain this unexpected behavior?
CharSequence is actually an interface which classes like String and StringBuilder implements. The reason why the result of subSequence(0, 1) isn't equal to subSequence.reversed() is because of the actual types they return.
The subSequence(0, 1) call returns a String, while reversed() returns a StringBuilder. The equals-method will therefore return false because the types are different.
It will work as you would expect if you call toString() on the result of reversed():
val reversed = subSequence.reversed().toString()
println("$subSequence == $reversed: ${subSequence == reversed}") // Prints a == a: true
Converting back to a String fixes the issue because then the correct (expected) eqauals is applied:
val s = "a"
val subSequence = s.subSequence(0, 1)
println(subSequence.reversed() == subSequence.reversed()) //false
println(subSequence.reversed().toString() == subSequence.reversed().toString()) //true
Note that you are probably confused by what is shown by toString and how equality (equals) behaves.
What you see is the output of toString(). Any type can decide how it's object's string representation might look like by overriding that method. This however has no influence on how objects of that type are compared against each other. That is where equals (in some cases also compare) comes in.
Others wrote something about that the underlying type of the objects to compare isn't equal (one side StringBuilder and the other String). The actual problem however is that of the equals-method. It could be (usually it isn't done so for various reasons), that equals for a certain type supports equality of different types of objects (such a behaviour (would) should be mentioned in the interface at least). If nothing is specified one can assume that the default equality from Object.equals holds.
In this case however the CharSequence-javadoc already states the following about equality (emphasis mine):
This interface does not refine the general contracts of the equals and hashCode methods. The result of testing two objects that implement CharSequence for equality is therefore, in general, undefined. Each object may be implemented by a different class, and thereis no guarantee that each class will be capable of testing its instancesfor equality with those of the other. It is therefore inappropriate to usearbitrary CharSequence instances as elements in a set or as keys ina map.
So summarizing: forget that you got a String or StringBuilder from subSequence and reversed. The method contract specifies CharSequence and as such you must handle it as CharSequence. There is no guarantee that those functions will still return a String or StringBuilder in future.

Elm "implies" function

I'm looking for an Elm function that does the following:
if e then
Just a
else
Nothing
For example, I am looking for an operator (=>) : Bool -> a -> Maybe a (binary function is fine also) that can be used like this
(x == 42) => "yes"
and will return Just "yes" if x == 42 and Nothing otherwise.
Clearly, I can use the if-then-else to accomplish the same thing, but I curious if such a function already exists.
The Elm Fancy Search tool is great for this kind of search. You can type in a function signature or name and see where it is used across all packages listed on package.elm-lang.org.
At the current time, that function signature exists in two packages under the function name when:
krisajenkins/elm-exts/27.4.0: Exts.Maybe.when: When test returns true, return Just value, otherwise return Nothing.
Gizra/elm-essentials/1.2.0: Gizra.Maybe.when: Create a Just a if condition is True, otherwise Nothing

Kotlin: What do the unary plus/minus operators do on numbers?

I've noticed in Kotlin that there are already defined unaryPlus and unaryMinus operators on all of the number types.
What's the purpose of these operators? Are they in some way connected to the prefix forms of inc and dec?
Others have defined the basic meaning of unaryMinus and unaryPlus, and in reality on numeric types they may not actually even be called as functions. For example, coding +x or x.unaryPlus() generates the same bytecode (where x is type Int):
ILOAD 1
ISTORE 2
And the code -x or x.unaryMinus() generates the identical bytecode:
ILOAD 1
INEG
ISTORE 2
But there is more going on that this...
So why does the compiler even generate anything for +x? Some people will say that +x and x.unaryPlus() doesn't do anything, and that -x and x.unaryMinus() only reverses the sign. That isn't correct. In Java it is more complicated because it can involve widening and unboxing, see Unary Numeric Promotion which explains the full consequences of these operators. This has consequences for boxed values and types smaller than Int. For value of type Short and Byte these operators will return a new unboxed value widened of type Int. And since both operators have this more hidden functionality then both must generate bytecode even if you don't think +x does anything. By the way, this is similar to what C language does and it is called Usual Arithmetic Conversions.
Therefore this code is invalid:
val x: Short = 1
val y1: Short = +x // incompatible types
val y2: Short = x.unaryPlus() // incompatible types
val z1: Short = -x // incompatible types
val z2: Short = x.unaryMinus() // incompatible types
In these numeric cases on the base numeric types they are just compiler magic to allow for the idea of these operators to be equated to operator functions that you might want to overload in other classes.
For other uses such as Operator Overloading...
But they are there for more than just mathematical use and can be used on any class as an operator. Kotlin exposes operators as functions so that you can apply operator overloading on a specific set of operators which include unaryMinus and unaryPlus.
I could use these to define operators for my own or existing classes. For example I have a Set<Things> where Things is an enum class along with an unaryMinus() operator to negate the contents of the finite set of options:
enum class Things {
ONE, TWO, THREE, FOUR, FIVE
}
operator fun Set<Things>.unaryMinus() = Things.values().toSet().minus(this)
And then I can negate my enum set whenever I want:
val current = setOf(Things.THREE, Things.FIVE)
println(-current) // [ONE, TWO, FOUR]
println(-(-current)) // [THREE, FIVE]
Notice that I had to declare my extension function with the modifier operator or this will not work. The compiler will remind you if you forget this when you try to use the operator:
Error:(y, x) Kotlin: 'operator' modifier is required on 'unaryMinus' in 'com.my.favorite.package.SomeClass'
These operators are the signs of the integers. Here are some examples:
+5 calls 5.unaryPlus() and returns 5.
-5 calls 5.unaryMinus() and returns -5.
-(-5) calls 5.unaryMinus().unaryMinus() and returns 5.
The purpose of those operators is to be able to write:
val a = System.nanoTime()
val b = -a // a.unaryMinus()
val c = +b // b.unaryPlus()
They are not directly related to ++/inc and --/dec operators however they can be used in conjunction.
Notice that the following expressions are different:
--a // a = a.dec()
-(-a) // a.unaryMinus().unaryMinus()
fun main(){
var a = 34
var b = 56
println("Orignal value:"+ a)
println("Orignal value:"+ b
//The value will not change using .unaryPlus() will generate bytecode
println("After unary plus:" + a.unaryPlus())
//The value will invert the sign using .unaryMinus() will generate bytecode
println("After unary minus:" + b.unaryMinus())
}
Solution:
Orignal value:34
Orignal value:56
After unary plus:35
After unary minus:-55