How can I find overloaded operators in Kotlin? - kotlin

Given that there are plenty of overloaded operators in Kotlin standard library how can I find them and their corresponding actions for each stdlib's class that declares them?
Example: recently I have discovered that += adds an element to MutableCollection.
I could have done it by going to MutableCollections.kt and finding there a declaration ...operator...plusAssign(t: T) but ofc I had no idea that it exists and can be found exactly in that file.
Maybe there is any official reference to see them in one place?

In Operator overloading documentation page, you will find Augmented assignments.
You can use either List<T> += T or List<T>.plusAssign(T).
If you want to quickly lookup mini-doc (and you are using IntelliJ/Android Studio) you can Hold CTRL + Q, it would show a mini dialog containing enough info.

Operator overloads can be defined anywhere(including outside the standard library), so it is not practical to make a list of all operator overloads.
You can find a list of all overloads in the documentation.
To summarize the documentation the following can be overloaded:
+a a.unaryPlus()
-a a.unaryMinus()
!a a.not()
a++ a.inc()
a-- a.dec()
a + b a.plus(b)
a - b a.minus(b)
a * b a.times(b)
a / b a.div(b)
a % b a.rem(b), a.mod(b) (deprecated)
a..b a.rangeTo(b)
a[i] a.get(i)
a[i, j] a.get(i, j)
a[i_1, ..., i_n] a.get(i_1, ..., i_n)
a[i] = b a.set(i, b)
a[i, j] = b a.set(i, j, b)
a[i_1, ..., i_n] = b a.set(i_1, ..., i_n, b)
a() a.invoke()
a(i) a.invoke(i)
a(i, j) a.invoke(i, j)
a(i_1, ..., i_n) a.invoke(i_1, ..., i_n)
a += b a.plusAssign(b)
a -= b a.minusAssign(b)
a *= b a.timesAssign(b)
a /= b a.divAssign(b)
a %= b a.remAssign(b), a.modAssign(b) (deprecated)
a == b a?.equals(b) ?: (b === null)
a != b !(a?.equals(b) ?: (b === null))
a > b a.compareTo(b) > 0
a < b a.compareTo(b) < 0
a >= b a.compareTo(b) >= 0
a <= b a.compareTo(b) <= 0

Related

What does mpn_invert_3by2 in mini-gmp do?

I really wonder the answer to this question. and I used python to calculate:
def inv(a):
return ((1 << 96) - 1) // (a << 32)
Why is python's result different from mpn_invert_limb's?
/* The 3/2 inverse is defined as
m = floor( (B^3-1) / (B u1 + u0)) - B
*/
B should be 2^32
And what is the use of mpn invert_limb?
Python code:
def inv(a):
return ((1 << 96) - 1) // (a << 32)
a = 165536
b = inv(a)
print(b & (2 ** 32 - 1))
C code:
int main()
{
mp_limb_t a = 16636;
mp_limb_t b;
b = mpn_invert_limb(a);
printf("a = %u, b = %u\n", a, b);
printf("a = %X, b = %X\n", a, b);
return 0;
}
Python output:
3522819686
C output:
a = 165536, b = 3165475657
a = 286A0, b = BCAD5349
Calling mpn_invert_limb only makes sense when your input is full-sized (has its high bit set). If the input isn't full sized then the quotient would be too big to fit in a single limb whereas in the full sized case its only 1 bit too big hence the subtraction of B in the definition.
I actually can't even run with your input of 16636, I get a division by 0 because this isn't even half a limb. Anyway, if I replace that value by a<<17 then I get a match between your Python and C. This shifting to make the top bit be set is what mini-gmp does in its usage of the function.

Hofstadter Female and Male sequences in SML

This is my first SML program. I am trying to write a function that returns the first number to the nth number of Hofstadter's Female or Male sequence in list form. What I have so far is:
val m = fn (n) => if n = 0 then 1 :: [] else m f (n - 1);
val f = fn (n) => if n = 0 then 0 :: [] else f m (n - 1);
You can learn about the sequence here:
https://en.wikipedia.org/wiki/Hofstadter_sequence#Hofstadter_Female_and_Male_sequences
The error that I am getting is:
[opening sequence.sml]
sequence.sml:1.49 Error: unbound variable or constructor: f
sequence.sml:1.47-1.58 Error: operator is not a function [tycon mismatch]
operator: int list
in expression:
(m <errorvar>) (n - 1)
val it = () : unit
How can I correct this?
I ended up taking this approach:
fun
m (n) = if n = 0 then 0 else n - (f (m (n - 1)))
and
f (n) = if n = 0 then 1 else n - (m (f (n - 1)));
val seq = fn n => List.tabulate((n), f);
It is quite slow. If anybody has a faster version, then I'd love to see it.
Although you have already fixed them, there were two problems with your original approach:
Function application is left-associative in SML so m f (n - 1) was being interpreted as (m f) (n - 1), not the desired m (f (n - 1)). You can fix this by explicitly specifying the bracketing m (f (n - 1)).
To be able to call f from m and m from f, you need to use the keyword fun instead of val on the first declaration (to make the function recursive), and the keyword and instead of fun or val on the second declaration (to make the function mutually recursive with the first function). This would look like
fun f n = ... (* I can call f or m from here! *)
and m n = ... (* I can call f or m from here! *)
To make it faster, you can memoize! The trick is to make f and m take as arguments memoized versions of themselves.
(* Convenience function: Update arr[i] to x, and return x. *)
fun updateAndReturn arr i x = (Array.update (arr, i, SOME x); x)
(*
* Look up result of f i in table; if it's not found, calculate f i and
* store in the table. The token is used so that deeper recursive calls
* to f can also try to store in the table.
*)
fun memo table f token i =
case Array.sub (table, i)
of NONE => updateAndReturn table i (f token i)
| SOME x => x
(*
* Given f, g, and n : int, returns a tuple (f', g') where f' and g' are memoized
* versions of f and g, respectively. f' and g' are defined only on the domain
* [0, n).
*)
fun memoizeMutual (f, g) n =
let
val fTable = Array.array (n, NONE)
val gTable = Array.array (n, NONE)
fun fMemo i = memo fTable f (fMemo, gMemo) i
and gMemo i = memo gTable g (gMemo, fMemo) i
in
(fMemo, gMemo)
end
fun female _ 0 = 1
| female (f, m) n = n - m (f (n - 1))
fun male _ 0 = 0
| male (m, f) n = n - f (m (n - 1))
fun hofstadter upTo =
let
val (male', female') = memoizeMutual (male, female) upTo
in
(List.tabulate (upTo, male'), List.tabulate (upTo, female'))
end
I renamed f and m to female and male. The memoized fMemo and gMemo are threaded through female and male by memoizeMutual. Interestingly, if we call male', then results for both male' and female' are memoized.
To confirm it's indeed faster, try evaluating hofstadter 10000. It's much faster than the forever that your version would take.
As a final note, the only recursive functions are fMemo and gMemo. Every other function I wrote could be written as an anonymous function (val memoizeMutual = fn ..., val female = fn ..., etc.), but I chose not to do so because the syntax for writing recursive functions is much more compact in SML.
To generalize this, you could replace the array version of memoizing with something like a hash table. Then we wouldn't have to specify the size of the memoization up front.

Weird syntax error

data A = B | C Int
implementation Semigroup A where
B <+> x = x
x <+> B = x
C m <+> C n = C (m + n)
gives me a syntax error of
./Nodes/Test.idr:3:1: error: expected: ";",
"|", declaration, end of input
implementation Semigroup A where
^
Type checking ./Nodes/Test.idr
in Idris 0.11.2. Removing implementation gives instead this message:
./Nodes/Test.idr:3:13: error: expected: "#",
"with", argument expression,
constraint argument,
function right hand side,
implicit function argument,
with pattern
Semigroup A where
^
Type checking ./Nodes/Test.idr
Should I get an error message? I can't see anything wrong with the syntax.
Thanks.
You cannot use infix operators in implementations (for now, I guess). Instead, wrap them to prefixes:
data A = B | C Int
implementation Semigroup A where
(<+>) B x = x
(<+>) x B = x
(<+>) (C m) (C n) = C (m + n)

How do I “flatten” a list of lists in perl 6?

Let's say I want all permutations of 2 letters out of a, b and c.
I can do:
my #perm = <a b c>.combinations(2)».permutations;
say #perm;
# [((a b) (b a)) ((a c) (c a)) ((b c) (c b))]
which is close, but not exactly what I need.
How do I “flatten” this so that I get:
# [(a b) (b a) (a c) (c a) (b c) (c b)]
?
See also "a better way to accomplish what I (OP) wanted".
See also "Some possible solutions" answer to "How can I completely flatten a Raku list (of lists (of lists) … )" question.
Add a subscript
my \perm = <a b c>.combinations(2)».permutations;
say perm; # (((a b) (b a)) ((a c) (c a)) ((b c) (c b)))
say perm[*]; # (((a b) (b a)) ((a c) (c a)) ((b c) (c b)))
say perm[*;*]; # ((a b) (b a) (a c) (c a) (b c) (c b))
say perm[*;*;*] # (a b b a a c c a b c c b)
Notes
I used a non-sigil'd variable because I think it's a bit clearer what's going on for those who don't know Raku.
I didn't append the subscript to the original expression but I could have:
my \perm = <a b c>.combinations(2)».permutations[*;*];
say perm; # ((a b) (b a) (a c) (c a) (b c) (c b))
Ultimately, you are building your list the wrong way to begin with. You can slip your permutations into the outer list like this.
<a b c>.combinations(2).map(|*.permutations);
Which yields the following list
((a b) (b a) (a c) (c a) (b c) (c b))
According to the Bench module, this is about 300% faster than doing
<a b c>.combinations(2).map(*.permutations)[*;*]
By inserting slips as appropriate, eg via
<a b c>.combinations(2).map(*.permutations.Slip).Array
or
[ slip .permutations for <a b c>.combinations(2) ]
Invoking .Array in the first example is unnecessary if you're fine with a Seq, and can be replaced with calls to .list or .cache (supplied by PositionalBindFailover) if mutability is not needed.
In the second example, the prefix | operator could be used instead of the slip sub.
my #perm = <a b c>.combinations(2)».permutations;
dd [ #perm.map(*.Slip) ]
# OUTPUT«[("a", "b"), ("b", "a"), ("a", "c"), ("c", "a"), ("b", "c"), ("c", "b")]␤»
However, you may be better of to destructure the LoL when you use it later in the program. A map on a long list can take a jolly long time.

How can I express the term ( a < b ? 0 : 1 ) using only bitwise or arithmetic operators?

Assuming the variables a and b are 32 bit integers is there a way to compare the two and return 0 if a < b and 1 if a >= b without using a ternary nor a comparison operator?
You can do this, but it's not pretty.
The problem is, as mentioned, overflow. But you can work around it, like this:
return ((x - y) ^ ((x ^ y) & ((x - y) ^ x))) >>> 31;
For the signed version, or
return ((~x & y) | ((~x | y) & (x - y))) >>> 31;
For the unsigned version.
The >>> there is an unsigned right shift, as in Java.
Use them with x = b, y = a to make them match your function.
You can find those (and others) in Hacker's Delight, under the name "comparison predicates".
First we take the difference of the two numbers. Then we are checking the sign using the fact that numbers are rappresented as complement of two.
int Compare(int a, int b)
{
int c = a - b;
int k = (c >> 31) & 1 ^ 1;
return k;
}