Is there a straightforward way to check if something is a mixin? - mixins

Raku mixins have two (or more) natures, combining several values in the same container, or values along with roles. However, there is not, as far as I can tell, a straightforward way to check for "mixinity" in a variable that has not been created by you.
This might be a trick
my $foo = 3 but Stringy;
say $foo.^name ~~ /\+/;# OUTPUT: «「+」␤»
But is there any other property I'm missing that would allow to look this up directly?

I think you're missing the ^roles and ^parents meta-methods:
my $foo = 3 but Stringy;
dd $foo.^roles; # (Stringy, Real, Numeric)
dd $foo.^parents; # (Int,)

TL;DR My unreliable solution[1] is simpler and faster than your unreliable solution[2] and should work for question Y and maybe question X[3]:
sub is-mixin ($object) { $object.^is_mixin =:= 1 }
say is-mixin 3; # False
say is-mixin 3 but 'bar'; # True
Footnotes
[1] "Warning: [role Metamodel::Mixins] is part of the Rakudo implementation, and is not a part of the language specification."
[2] I haven't searched roast but would imagine that the use of + in type names is just a convention, not a part of the language specification.
[3] I found your question to be an example of either the XY problem, per my first comment below it; and/or of terminological confusion, per my second. The rest of this answer explains what I mean.
Is there a straightforward way to check if a container is a mixin?
The word "container" has a technical meaning in Raku. It refers to a value that follows Raku's container protocol. The container protocol applies when a value is followed by = to invoke "assignment".
What you are asking about appears to have nothing to do with such a container, as something distinct from a value. And there's good reason to think that that doesn't matter to you -- that what you are just interested in is testing if a value is a mixin, and the "container" aspect is a red-herring, either because you didn't mean "container" in the usual sense in Raku, or because it doesn't matter anyway because a container is a value, so whatever works for testing a value will work for testing a container.
For example, looking at your "trick":
my $foo = 3 but Stringy;
say $foo.^name ~~ /\+/;# OUTPUT: «「+」␤»
This trick is unrelated to any container aspect using the normal technical use of the word "container" in Raku. You get the same result if you write the following that doesn't involve a container: say (3 but Stringy).^name ~~ /\+/;# OUTPUT: «「+」␤».
So in my solution I've presumed you just meant a value, knowing that it actually doesn't matter whether or not your ultimate focus is on a container.
If I'm wrong about my presumption, and it makes a difference, I urge you to explain the X of what it is you're trying to do rather than just the Y.

Your trick makes your code brittle because it doesn't expect
$foo.^set_name('The Spanish Inquisition');
Of course nobody does :)
You better just ask the Rakudo Metamodel:
say $foo.^is_mixin; # OUTPUT: «1␤»
Two things to note:
The is_mixin metamethod does not return a Bool
Like the name metamethod it is specific to the Rakudo implementation of Raku

Related

Why to use := in Scala? [duplicate]

What is the difference between = and := in Scala?
I have googled extensively for "scala colon-equals", but was unable to find anything definitive.
= in scala is the actual assignment operator -- it does a handful of specific things that for the most part you don't have control over, such as
Giving a val or var a value when it's created
Changing the value of a var
Changing the value of a field on a class
Making a type alias
Probably others
:= is not a built-in operator -- anyone can overload it and define it to mean whatever they like. The reason people like to use := is because it looks very assignmenty and is used as an assignment operator in other languages.
So, if you're trying to find out what := means in the particular library you're using... my advice is look through the Scaladocs (if they exist) for a method named :=.
from Martin Odersky:
Initially we had colon-equals for assignment—just as in Pascal, Modula, and Ada—and a single equals sign for equality. A lot of programming theorists would argue that that's the right way to do it. Assignment is not equality, and you should therefore use a different symbol for assignment. But then I tried it out with some people coming from Java. The reaction I got was, "Well, this looks like an interesting language. But why do you write colon-equals? What is it?" And I explained that its like that in Pascal. They said, "Now I understand, but I don't understand why you insist on doing that." Then I realized this is not something we wanted to insist on. We didn't want to say, "We have a better language because we write colon-equals instead of equals for assignment." It's a totally minor point, and people can get used to either approach. So we decided to not fight convention in these minor things, when there were other places where we did want to make a difference.
from The Goals of Scala's Design
= performs assignment. := is not defined in the standard library or the language specification. It's a name that is free for other libraries or your code to use, if you wish.
Scala allows for operator overloading, where you can define the behaviour of an operator just like you could write a method.
As in other languages, = is an assignment operator.
The is no standard operator I'm aware of called :=, but could define one with this name. If you see an operator like this, you should check up the documentation of whatever you're looking at, or search for where that operator is defined.
There is a lot you can do with Scala operators. You can essentially make an operator out of virtually any characters you like.

Progress 4GL Performance Gains By Avoiding Database Write Operation

At my company we've recently been working on a modification to an existing program that used the following logic to perform some database field assignments:
db-buffer1.field1 = if db-buffer1.field1 <> db-buffer2.field2
then db-buffer2.field2
else db-buffer1.field1
I'm not 100% sure of the original programmer's intention here. Can anyone help me understand the value in comparing whether or not the field values are different before deciding whether to assign the new field?
If the comparison is 'false' and we end up assigning db-buffer1.field1 = db-buffer1.field1 do we avoid a write operation on the database?
Also note that this example is part of a larger ASSIGN statement that contains several fields running similar assignment/comparison logic. Does that have any effect on the value of this additional code? (i.e. Do all comparisons in the ASSIGN statement have to succeed in order to avoid a DB write?)
An "IF function" on the right hand side of an expression is a lot like a "ternary operator" in C or Javascript (the "?:" construct).
It only impacts the portion of the ASSIGN that it is part of. When I write code using those I always encase it in parens to make it clear. Like so:
assign
a = ( if x = y then b else c )
z = 2
.
Whether or not a WRITE happens depends a lot on the rest of the code.
Judging only by this snippet you are going to write SOMETHING (at least logically). db-buffer.field1 is going to get a value assigned to it regardless. The IF logic on the right-hand side is just picking if it will be field1 or field2. In the case that boils down to field1 = field1 you might hope that some lower layer will optimize the write out of existence. I don't see your Progress version posted but if it is v9 or better then it may very well be optimized away. (Prior to v9 it would not have been.)
If you really want to "avoid the write" at the application level you should code it like this:
if field1 <> field2 then
assign
field1 = field2
.
This form does not use the IF function, it is just a normal IF ... THEN statement. It is much clearer and it does not depend on optimizations at a lower level. Of course the snippet shown is said to be part of a larger ASSIGN -- so it may or may not be sensible to break it out and write it as I've shown. But it would be worth thinking about.
It appears that the programmer is checking if field1 is not equal to field2 go ahead and update it.
They might as well simply use the following since either way the field is being assigned:
assign db-buffer1.field1 = db-buffer2.field2.
When using the ASSIGN statement (recommended always), from a logical perspective you have to keep in mind that each line is assigned separately.
Tom has a great answer here that gives more information regarding efficiency/history of the ASSIGN statement.
I would be very interested in seeing the rest of the assign statement, but I would also get rid of the if logic in this case as it adds no value, just and extra instruction. As Terry stated above
ASSIGN db-buffer1.field1 = db-buffer2.field2.

What is the difference between = and := in Scala?

What is the difference between = and := in Scala?
I have googled extensively for "scala colon-equals", but was unable to find anything definitive.
= in scala is the actual assignment operator -- it does a handful of specific things that for the most part you don't have control over, such as
Giving a val or var a value when it's created
Changing the value of a var
Changing the value of a field on a class
Making a type alias
Probably others
:= is not a built-in operator -- anyone can overload it and define it to mean whatever they like. The reason people like to use := is because it looks very assignmenty and is used as an assignment operator in other languages.
So, if you're trying to find out what := means in the particular library you're using... my advice is look through the Scaladocs (if they exist) for a method named :=.
from Martin Odersky:
Initially we had colon-equals for assignment—just as in Pascal, Modula, and Ada—and a single equals sign for equality. A lot of programming theorists would argue that that's the right way to do it. Assignment is not equality, and you should therefore use a different symbol for assignment. But then I tried it out with some people coming from Java. The reaction I got was, "Well, this looks like an interesting language. But why do you write colon-equals? What is it?" And I explained that its like that in Pascal. They said, "Now I understand, but I don't understand why you insist on doing that." Then I realized this is not something we wanted to insist on. We didn't want to say, "We have a better language because we write colon-equals instead of equals for assignment." It's a totally minor point, and people can get used to either approach. So we decided to not fight convention in these minor things, when there were other places where we did want to make a difference.
from The Goals of Scala's Design
= performs assignment. := is not defined in the standard library or the language specification. It's a name that is free for other libraries or your code to use, if you wish.
Scala allows for operator overloading, where you can define the behaviour of an operator just like you could write a method.
As in other languages, = is an assignment operator.
The is no standard operator I'm aware of called :=, but could define one with this name. If you see an operator like this, you should check up the documentation of whatever you're looking at, or search for where that operator is defined.
There is a lot you can do with Scala operators. You can essentially make an operator out of virtually any characters you like.

The case for point free style in Scala

This may seem really obvious to the FP cognoscenti here, but what is point free style in Scala good for? What would really sell me on the topic is an illustration that shows how point free style is significantly better in some dimension (e.g. performance, elegance, extensibility, maintainability) than code solving the same problem in non-point free style.
Quite simply, it's about being able to avoid specifying a name where none is needed, consider a trivial example:
List("a","b","c") foreach println
In this case, foreach is looking to accept String => Unit, a function that accepts a String and returns Unit (essentially, that there's no usable return and it works purely through side effect)
There's no need to bind a name here to each String instance that's passed to println. Arguably, it just makes the code more verbose to do so:
List("a","b","c") foreach {println(_)}
Or even
List("a","b","c") foreach {s => println(s)}
Personally, when I see code that isn't written in point-free style, I take it as an indicator that the bound name may be used twice, or that it has some significance in documenting the code. Likewise, I see point-free style as a sign that I can reason about the code more simply.
One appeal of point-free style in general is that without a bunch of "points" (values as opposed to functions) floating around, which must be repeated in several places to thread them through the computation, there are fewer opportunities to make a mistake, e.g. when typing a variable's name.
However, the advantages of point-free are quickly counterbalanced in Scala by its meagre ability to infer types, a fact which is exacerbated by point-free code because "points" serve as clues to the type inferencer. In Haskell, with its almost-complete type inferencing, this is usually not an issue.
I see no other advantage than "elegance": It's a little bit shorter, and may be more readable. It allows to reason about functions as entities, without going mentally a "level deeper" to function application, but of course you need getting used to it first.
I don't know any example where performance improves by using it (maybe it gets worse in cases where you end up with a function when a method would be sufficient).
Scala's point-free syntax is part of the magic Scala operators-which-are-really-functions. Even the most basic operators are functions:
For example:
val x = 1
val y = x + 1
...is the same as...
val x = 1
val y = x.+(1)
...but of course, the point-free style reads more naturally (the plus appears to be an operator).

Methods of simplifying ugly nested if-else trees in C#

Sometimes I'm writing ugly if-else statements in C# 3.5; I'm aware of some different approaches to simplifying that with table-driven development, class hierarchy, anonimous methods and some more.
The problem is that alternatives are still less wide-spread than writing traditional ugly if-else statements because there is no convention for that.
What depth of nested if-else is normal for C# 3.5? What methods do you expect to see instead of nested if-else the first? the second?
if i have ten input parameters with 3 states in each, i should map functions to combination of each state of each parameter (really less, because not all the states are valid, but sometimes still a lot). I can express these states as a hashtable key and a handler (lambda) which will be called if key matches.
It is still mix of table-driven, data-driven dev. ideas and pattern matching.
what i'm looking for is extending for C# such approaches as this for scripting (C# 3.5 is rather like scripting)
http://blogs.msdn.com/ericlippert/archive/2004/02/24/79292.aspx
Good question. "Conditional Complexity" is a code smell. Polymorphism is your friend.
Conditional logic is innocent in its infancy, when it’s simple to understand and contained within a
few lines of code. Unfortunately, it rarely ages well. You implement several new features and
suddenly your conditional logic becomes complicated and expansive. [Joshua Kerevsky: Refactoring to Patterns]
One of the simplest things you can do to avoid nested if blocks is to learn to use Guard Clauses.
double getPayAmount() {
if (_isDead) return deadAmount();
if (_isSeparated) return separatedAmount();
if (_isRetired) return retiredAmount();
return normalPayAmount();
};
The other thing I have found simplifies things pretty well, and which makes your code self-documenting, is Consolidating conditionals.
double disabilityAmount() {
if (isNotEligableForDisability()) return 0;
// compute the disability amount
Other valuable refactoring techniques associated with conditional expressions include Decompose Conditional, Replace Conditional with Visitor, Specification Pattern, and Reverse Conditional.
There are very old "formalisms" for trying to encapsulate extremely complex expressions that evaluate many possibly independent variables, for example, "decision tables" :
http://en.wikipedia.org/wiki/Decision_table
But, I'll join in the choir here to second the ideas mentioned of judicious use of the ternary operator if possible, identifying the most unlikely conditions which if met allow you to terminate the rest of the evaluation by excluding them first, and add ... the reverse of that ... trying to factor out the most probable conditions and states that can allow you to proceed without testing of the "fringe" cases.
The suggestion by Miriam (above) is fascinating, even elegant, as "conceptual art;" and I am actually going to try it out, trying to "bracket" my suspicion that it will lead to code that is harder to maintain.
My pragmatic side says there is no "one size fits all" answer here in the absence of a pretty specific code example, and complete description of the conditions and their interactions.
I'm a fan of "flag setting" : meaning anytime my application goes into some less common "mode" or "state" I set a boolean flag (which might even be static for the class) : for me that simplifies writing complex if/then else evaluations later on.
best, Bill
Simple. Take the body of the if and make a method out of it.
This works because most if statements are of the form:
if (condition):
action()
In other cases, more specifically :
if (condition1):
if (condition2):
action()
simplify to:
if (condition1 && condition2):
action()
I'm a big fan of the ternary operator which get's overlooked by a lot of people. It's great for assigning values to variables based on conditions. like this
foobarString = (foo == bar) ? "foo equals bar" : "foo does not equal bar";
Try this article for more info.
It wont solve all your problems, but it is very economical.
I know that this is not the answer you are looking for, but without context your questions is very hard to answer. The problem is that the way to refactor such a thing really depends on your code, what it is doing, and what you are trying to accomplish. If you had said that you were checking the type of an object in these conditionals we could throw out an answer like 'use polymorphism', but sometimes you actually do just need some if statements, and sometimes those statements can be refactored into something more simple. Without a code sample it is hard to say which category you are in.
I was told years ago by an instructor that 3 is a magic number. And as he applied it it-else statements he suggested that if I needed more that 3 if's then I should probably use a case statement instead.
switch (testValue)
{
case = 1:
// do something
break;
case = 2:
// do something else
break;
case = 3:
// do something more
break;
case = 4
// do what?
break;
default:
throw new Exception("I didn't do anything");
}
If you're nesting if statements more than 3 deep then you should probably take that as a sign that there is a better way. Probably like Avirdlg suggested, separating the nested if statements into 1 or more methods. If you feel you are absolutely stuck with multiple if-else statements then I would wrap all the if-else statements into a single method so it didn't ugly up other code.
If the entire purpose is to assign a different value to some variable based upon the state of various conditionals, I use a ternery operator.
If the If Else clauses are performing separate chunks of functionality. and the conditions are complex, simplify by creating temporary boolean variables to hold the true/false value of the complex boolean expressions. These variables should be suitably named to represent the business sense of what the complex expression is calculating. Then use the boolean variables in the If else synatx instead of the complex boolean expressions.
One thing I find myself doing at times is inverting the condition followed by return; several such tests in a row can help reduce nesting of if and else.
Not a C# answer, but you probably would like pattern matching. With pattern matching, you can take several inputs, and do simultaneous matches on all of them. For example (F#):
let x=
match cond1, cond2, name with
| _, _, "Bob" -> 9000 // Bob gets 9000, regardless of cond1 or 2
| false, false, _ -> 0
| true, false, _ -> 1
| false, true, _ -> 2
| true, true, "" -> 0 // Both conds but no name gets 0
| true, true, _ -> 3 // Cond1&2 give 3
You can express any combination to create a match (this just scratches the surface). However, C# doesn't support this, and I doubt it will any time soon. Meanwhile, there are some attempts to try this in C#, such as here: http://codebetter.com/blogs/matthew.podwysocki/archive/2008/09/16/functional-c-pattern-matching.aspx. Google can turn up many more; perhaps one will suit you.
try to use patterns like strategy or command
In simple cases you should be able to get around with basic functional decomposition. For more complex scenarios I used Specification Pattern with great success.