Range ordering and inequality comparison - python-3.x

I was trying to recreate Python's range as a learning exercise, and noticed that ranges had range.__gt__, range.__ge__ etc. attribute. It was specifically defined in range, as range also has 8 attributes with the qualified name of object.__...__.
I was wondering what the range comparisons are used for. Any attempt at range(*x) <= range(*y) raises a TypeError: unorderable types: range() > range()

The Python 3 range object defines the following rich comparisons (taken from the C source):
static PyObject *
range_richcompare(PyObject *self, PyObject *other, int op)
{
int result;
if (!PyRange_Check(other))
Py_RETURN_NOTIMPLEMENTED;
switch (op) {
case Py_NE:
case Py_EQ:
result = range_equals((rangeobject*)self, (rangeobject*)other);
if (result == -1)
return NULL;
if (op == Py_NE)
result = !result;
if (result)
Py_RETURN_TRUE;
else
Py_RETURN_FALSE;
case Py_LE:
case Py_GE:
case Py_LT:
case Py_GT:
Py_RETURN_NOTIMPLEMENTED;
default:
PyErr_BadArgument();
return NULL;
}
}
As you can see, the only comparisons that are actually implemented are NE and EQ which are for inequality and equality. The other comparisons, like larger-equals, larger-than, etc., are all Py_RETURN_NOTIMPLEMENTED, so while they are “technically” implemented (as in the builtin object defines the comparison methods), they throw a NotImplementedError.

Related

Is there a name for a trampoline class?

I'm designing a programming language and one feature I'd like to add is a cross between a trampoline function and a class. That is, a class which takes in a literal akin to a generic class taking in a type. I'm stuck on a name for these because I haven't encountered them in a language before, is there something which already means this concept or something close? Using trampoline class is an option, but if there's something that more accurately describes this or is already in use in another language I'd prefer to go with it to cut down on the amount of jargon required in the documentation.
Pseudo-code follows to illustrate this principle in case it is not clear from the above:
class Point<const int n> {
private float[n] _value;
Point() {
for (int i = 0; i < n; i++) {
this._value[i] = 0f;
}
}
Point(Point<o> other) {
for (int i = 0; i < min(n, o); i++) {
this._value[i] = 0f;
}
}
public static float operator [index] (optional float value = null) {
if (value != null) { this._value[index] = value; }
return (this._value[index]);
}
public static Point<max(o, p)> operator + (Point<const int o> p1, Point<const int p> p2) {
Point<min(o, p)> small = (p1.n < p2.n ? p1 : p2);
Point<min(o, p)> large = (p1.n < p2.n ? p2 : p1);
Point<max(o, p)> ret = new Point<max(o, p)>(large);
for (int i = 0; i < min(o, p); i++) { ret[i] += small[i] }
return (ret);
}
}
The term you are looking for is dependent types. It means that a type cannot only have type parameters (like generics), but a type can also be parameterized with arbitrary values (the dependent type parameters). For example, you can define the signature of a function that takes a number n and returns an array of length n.
Sadly, dependent type checking in general is undecidable. This is, because you have to calculate the range of possible values of the dependent type parameters while the type checking itself is executed. To actually type check the program, you have to check whether two pieces of code produce the same range of possible values. This is known as extensional function equality and this is the part that is known to be undecidable in general.
Now, it might be true that dependent type checking becomes decidable if only compile-time constants are used as dependent type parameters. However, I am not sure about that.
In the comments below, we figured out that the part that seems to be the dependent type parameter should actually not be used for the type checking. Instead, it can be seen as an implicit parameter. It is similar to implicit parameter passing in the Scala programming language.

Groovy "not instanceof" peculiarity

I have discovered behaviour that I hadn't anticipated within Groovy 2.4.7, 1.6.0 JVM when attempting to evaluate a not instanceof condition.
in summary:
class Foo {
static Boolean bar() {
String x = "Personally, I don't really like King Crimson"
return (!x instanceof Integer)
}
}
I would anticipate that Foo.bar() would return true because x is not an instance of Integer however Foo.bar() returns false. In contrast the following returns true:
class Foo {
static Boolean bar() {
String x = "Personally, I don't really like King Crimson"
return !(x instanceof Integer)
}
}
The issue is academic, but out of curiousity: is this a bug in the language or have I misunderstood how instanceof is supposed to work?
It's a case of operator precedence...
! occurs before instanceof, so it's actually checking:
(!x) instanceof Integer
So it's converting String to a boolean (!'Hello' is false as the string contains some text.
Then seeing if the boolean is an instanceof Integer (which it isn't)
hence false
If you put the ! outside the brackets (as in your second version) then it does the instanceof first, and negates the result, giving you the answer you'd expect
Edit for Groovy 3+
In groovy 3 there's a new way of doing this using !instanceof:
return x !instanceof Integer

How to specify character literal in groovy?

How do I specify a character literal in groovy since both 'a' and "a" result in string?
I do not want to declare a character variable just for this purpose.
Using the as keyword is the way to make a character literal in Groovy.
'a' as char
See the discussion here at Groovy's buglist.
If this is for a variable, you can also define the type, so:
import java.awt.image.*
new BufferedImage( 1, 1, BufferedImage.TYPE_INT_RGB ).with {
createGraphics().with {
// Declare the type
char aChar = 'a'
// Both ways are equivalent and work
assert fontMetrics.charWidth( aChar ) == fontMetrics.charWidth( 'a' as char )
dispose()
}
}
(apologies for the long example, but I had brain freeze, and couldn't think of a different standard java function that takes a char) ;-)
This also goes against the second line of the question, but I thought I'd add it for completeness
There a three ways to use char literals in Groovy:
char c = 'c' /* 1 */
'c' as char /* 2 */
(char) 'c' /* 3 */
println Character.getNumericValue(c) /* 1 */
println Character.getNumericValue('c' as char) /* 2 */
println Character.getNumericValue((char) 'c') /* 3 */
If you assign a String literal like 'c' to a variable, Groovy does the cast implicitly (see /* 1 * /). If you want use the String literals without variables, you have to cast them by using ...as char... (see /* 2 * /) or ...(char)... (see /* 3 * /).
The usage of char literals in methods without casting them is not possible as Groovy has only String literals which must be casted to char.
println Character.getNumericValue('c') // compile error
This response is rather late! But just stumbled upon it and wanted to add some clarification.
The more accurate Answer is unlike Java, Groovy does NOT have a character literal, but you can cast a string to a character. A literal is a value that is written exactly as it is to be interpreted, and the necessity of the type cast indicates it is NOT truly a literal.
Examples:
assert 'a'.class != Character.class
assert 'a'.class == String.class
assert ('a' as char).class == Character.class
assert ((char)'a').class == Character.class
char A = 'a'; // implicit coercion of string to char
assert A.class == Character.class
In contrast, both groovy and Java support numeric literals for int, long, double, and float, but do not support numeric literal for short.
Examples:
assert 42.class == Integer.class
assert 42l.class == Long.class
assert 42f.class == Float.class
assert 42d.class == Double.class
assert (42 as Short).class == Short.class

How does type promotion work in Groovy?

Consider the following code snippet -
def factorial(number) {
if(number == 1)
return number;
else
return number * factorial(number - 1);
}
println factorial(50)
println factorial(50).getClass()
println()
println 45**20
println ((45**20).getClass())
The output is -
0
class java.lang.Integer
1159445329576199417209625244140625
class java.math.BigInteger
Questions -
Why doesn't groovy automatically promote the result of number * factorial(number-1) to a BigInt in the first case?
Why is the output 0? Why isn't it some random number that we should get after integer overflow?
Old question but I'll try to answer both parts of the question:
Groovy documentation on arithmetic operations states that
binary operations involving subclasses of java.lang.Number automatically convert their arguments according to the following matrix (except for division, which is discussed below)
I won't paste the matrix but it specifies no casting to BigInteger or BigDecimal unless one of the operators is of one of these types.
In the case of division:
The division operators "/" and "/=" produce a Double result if either operand is either Float or Double and a BigDecimal result otherwise
I think that the table is not considering the power operator (**) since it's not present in Java and as stated in #tim_yates comment, power implementation uses BigInteger by default.
The code in DefaultGroovyMethods.java shows clearly that the power of int's is calculated using BigInteger's and if the result is small then is cast down to int again (And that's why (2**4).class is java.lang.Integer):
public static Number power(Integer self, Integer exponent) {
if (exponent >= 0) {
BigInteger answer = BigInteger.valueOf(self).pow(exponent);
if (answer.compareTo(BI_INT_MIN) >= 0 && answer.compareTo(BI_INT_MAX) <= 0) {
return answer.intValue();
} else {
return answer;
}
} else {
return power(self, (double) exponent);
}
}
To confirm the behaviour of other operations you can go to IntegerMath, LongMath or other classes in the org.codehaus.groovy.runtime.typehandling package
With Groovy, Integer.multiply( Integer ) always returns an Integer.
The factorial method starts overflowing around step 16.
At step 34, you end up with -2147483648 * -2147483648 which returns 0 so the result will always be 0
One fix is to change your method declaration to:
def factorial( BigInteger number ) {

C# 4.0 optional out/ref arguments

Does C# 4.0 allow optional out or ref arguments?
No.
A workaround is to overload with another method that doesn't have out / ref parameters, and which just calls your current method.
public bool SomeMethod(out string input)
{
...
}
// new overload
public bool SomeMethod()
{
string temp;
return SomeMethod(out temp);
}
If you have C# 7.0, you can simplify:
// new overload
public bool SomeMethod()
{
return SomeMethod(out _); // declare out as an inline discard variable
}
(Thanks #Oskar / #Reiner for pointing this out.)
As already mentioned, this is simply not allowed and I think it makes a very good sense.
However, to add some more details, here is a quote from the C# 4.0 Specification, section 21.1:
Formal parameters of constructors, methods, indexers and delegate types can be declared optional:
fixed-parameter:
attributesopt parameter-modifieropt type identifier default-argumentopt
default-argument:
= expression
A fixed-parameter with a default-argument is an optional parameter, whereas a fixed-parameter without a default-argument is a required parameter.
A required parameter cannot appear after an optional parameter in a formal-parameter-list.
A ref or out parameter cannot have a default-argument.
No, but another great alternative is having the method use a generic template class for optional parameters as follows:
public class OptionalOut<Type>
{
public Type Result { get; set; }
}
Then you can use it as follows:
public string foo(string value, OptionalOut<int> outResult = null)
{
// .. do something
if (outResult != null) {
outResult.Result = 100;
}
return value;
}
public void bar ()
{
string str = "bar";
string result;
OptionalOut<int> optional = new OptionalOut<int> ();
// example: call without the optional out parameter
result = foo (str);
Console.WriteLine ("Output was {0} with no optional value used", result);
// example: call it with optional parameter
result = foo (str, optional);
Console.WriteLine ("Output was {0} with optional value of {1}", result, optional.Result);
// example: call it with named optional parameter
foo (str, outResult: optional);
Console.WriteLine ("Output was {0} with optional value of {1}", result, optional.Result);
}
There actually is a way to do this that is allowed by C#. This gets back to C++, and rather violates the nice Object-Oriented structure of C#.
USE THIS METHOD WITH CAUTION!
Here's the way you declare and write your function with an optional parameter:
unsafe public void OptionalOutParameter(int* pOutParam = null)
{
int lInteger = 5;
// If the parameter is NULL, the caller doesn't care about this value.
if (pOutParam != null)
{
// If it isn't null, the caller has provided the address of an integer.
*pOutParam = lInteger; // Dereference the pointer and assign the return value.
}
}
Then call the function like this:
unsafe { OptionalOutParameter(); } // does nothing
int MyInteger = 0;
unsafe { OptionalOutParameter(&MyInteger); } // pass in the address of MyInteger.
In order to get this to compile, you will need to enable unsafe code in the project options. This is a really hacky solution that usually shouldn't be used, but if you for some strange, arcane, mysterious, management-inspired decision, REALLY need an optional out parameter in C#, then this will allow you to do just that.
ICYMI: Included on the new features for C# 7.0 enumerated here, "discards" is now allowed as out parameters in the form of a _, to let you ignore out parameters you don’t care about:
p.GetCoordinates(out var x, out _); // I only care about x
P.S. if you're also confused with the part "out var x", read the new feature about "Out Variables" on the link as well.
No, but you can use a delegate (e.g. Action) as an alternative.
Inspired in part by Robin R's answer when facing a situation where I thought I wanted an optional out parameter, I instead used an Action delegate. I've borrowed his example code to modify for use of Action<int> in order to show the differences and similarities:
public string foo(string value, Action<int> outResult = null)
{
// .. do something
outResult?.Invoke(100);
return value;
}
public void bar ()
{
string str = "bar";
string result;
int optional = 0;
// example: call without the optional out parameter
result = foo (str);
Console.WriteLine ("Output was {0} with no optional value used", result);
// example: call it with optional parameter
result = foo (str, x => optional = x);
Console.WriteLine ("Output was {0} with optional value of {1}", result, optional);
// example: call it with named optional parameter
foo (str, outResult: x => optional = x);
Console.WriteLine ("Output was {0} with optional value of {1}", result, optional);
}
This has the advantage that the optional variable appears in the source as a normal int (the compiler wraps it in a closure class, rather than us wrapping it explicitly in a user-defined class).
The variable needs explicit initialisation because the compiler cannot assume that the Action will be called before the function call exits.
It's not suitable for all use cases, but worked well for my real use case (a function that provides data for a unit test, and where a new unit test needed access to some internal state not present in the return value).
Use an overloaded method without the out parameter to call the one with the out parameter for C# 6.0 and lower. I'm not sure why a C# 7.0 for .NET Core is even the correct answer for this thread when it was specifically asked if C# 4.0 can have an optional out parameter. The answer is NO!
For simple types you can do this using unsafe code, though it's not idiomatic nor recommended. Like so:
// unsafe since remainder can point anywhere
// and we can do arbitrary pointer manipulation
public unsafe int Divide( int x, int y, int* remainder = null ) {
if( null != remainder ) *remainder = x % y;
return x / y;
}
That said, there's no theoretical reason C# couldn't eventually allow something like the above with safe code, such as this below:
// safe because remainder must point to a valid int or to nothing
// and we cannot do arbitrary pointer manipulation
public int Divide( int x, int y, out? int remainder = null ) {
if( null != remainder ) *remainder = x % y;
return x / y;
}
Things could get interesting though:
// remainder is an optional output parameter
// (to a nullable reference type)
public int Divide( int x, int y, out? object? remainder = null ) {
if( null != remainder ) *remainder = 0 != y ? x % y : null;
return x / y;
}
The direct question has been answered in other well-upvoted answers, but sometimes it pays to consider other approaches based on what you're trying to achieve.
If you're wanting an optional parameter to allow the caller to possibly request extra data from your method on which to base some decision, an alternative design is to move that decision logic into your method and allow the caller to optionally pass a value for that decision criteria in. For example, here is a method which determines the compass point of a vector, in which we might want to pass back the magnitude of the vector so that the caller can potentially decide if some minimum threshold should be reached before the compass-point judgement is far enough away from the origin and therefore unequivocally valid:
public enum Quadrant {
North,
East,
South,
West
}
// INVALID CODE WITH MADE-UP USAGE PATTERN OF "OPTIONAL" OUT PARAMETER
public Quadrant GetJoystickQuadrant([optional] out magnitude)
{
Vector2 pos = GetJoystickPositionXY();
float azimuth = Mathf.Atan2(pos.y, pos.x) * 180.0f / Mathf.PI;
Quadrant q;
if (azimuth > -45.0f && azimuth <= 45.0f) q = Quadrant.East;
else if (azimuth > 45.0f && azimuth <= 135.0f) q = Quadrant.North;
else if (azimuth > -135.0f && azimuth <= -45.0f) q = Quadrant.South;
else q = Quadrant.West;
if ([optonal.isPresent(magnitude)]) magnitude = pos.Length();
return q;
}
In this case we could move that "minimum magnitude" logic into the method and end-up with a much cleaner implementation, especially because calculating the magnitude involves a square-root so is computationally inefficient if all we want to do is a comparison of magnitudes, since we can do that with squared values:
public enum Quadrant {
None, // Too close to origin to judge.
North,
East,
South,
West
}
public Quadrant GetJoystickQuadrant(float minimumMagnitude = 0.33f)
{
Vector2 pos = GetJoystickPosition();
if (minimumMagnitude > 0.0f && pos.LengthSquared() < minimumMagnitude * minimumMagnitude)
{
return Quadrant.None;
}
float azimuth = Mathf.Atan2(pos.y, pos.x) * 180.0f / Mathf.PI;
if (azimuth > -45.0f && azimuth <= 45.0f) return Quadrant.East;
else if (azimuth > 45.0f && azimuth <= 135.0f) return Quadrant.North;
else if (azimuth > -135.0f && azimuth <= -45.0f) return Quadrant.South;
return Quadrant.West;
}
Of course, that might not always be viable. Since other answers mention C# 7.0, if instead what you're really doing is returning two values and allowing the caller to optionally ignore one, idiomatic C# would be to return a tuple of the two values, and use C# 7.0's Tuples with positional initializers and the _ "discard" parameter:
public (Quadrant, float) GetJoystickQuadrantAndMagnitude()
{
Vector2 pos = GetJoystickPositionXY();
float azimuth = Mathf.Atan2(pos.y, pos.x) * 180.0f / Mathf.PI;
Quadrant q;
if (azimuth > -45.0f && azimuth <= 45.0f) q = Quadrant.East;
else if (azimuth > 45.0f && azimuth <= 135.0f) q = Quadrant.North;
else if (azimuth > -135.0f && azimuth <= -45.0f) q = Quadrant.South;
else q = Quadrant.West;
return (q, pos.Length());
}
(Quadrant q, _) = GetJoystickQuadrantAndMagnitude();
if (q == Quadrant.South)
{
// Do something.
}
What about like this?
public bool OptionalOutParamMethod([Optional] ref string pOutParam)
{
return true;
}
You still have to pass a value to the parameter from C# but it is an optional ref param.
void foo(ref int? n)
{
return null;
}

Resources