dot operators on functions - programming-languages

I don't know if this is possible, but are there any languages where you can use a dot operator on a function per se. I'll give an example.
function blah returns type2
type 2 looks like this
{
data
number
}
when I call blah are there any languages that support blah.number, so that when it makes the function call and gets the type2, it then grabs number and returns that. I'm sorry if this is an obvious answer, but I couldn't even think of a good way to word it to google it.
I just ran into a situation that would be convienient to have that, rather then make an intermediate variable you just make sure you return the type.
I know that I could add a "get" function that would get the specific number variable from that type, but that's an additional function someone would have to add so I am excluding that as a option (as I can just return the type and access using a variable there isn't really a dire need for a new function).
EDIT: I feel like an idiot.....
EDIT # 2: For some reason I had it in my head that you couldn't do dot operations on functions, (I don't care about the parentheses I was just trying to give an example)
Edit # 3: Is there a name for this or is it still just a dot operation?

Well this works in C if the function returns a struct like this:
struct retval {
char * data;
int number;
};
retval foo() {
// do something and then return an instance of retval
}
// call
int a = foo().number;
I would like to know if there is any language that does not support something like this.
About Edit #3
The name would generally be member access, since all you do is to access a member of the return value. This could differ across languages though.

In most languages you can do Blah().Member ... the typing of a pair of parentheses won't kill you, will it? These languages include C, C++, Java, C# etc.

Yep, to the best of my knowledge, most modern languages (if not most languages in general) support this.

Maybe I misunderstand you, but in most languages, you can already do that.
in java for example, if you have a function get_foo() returning an object of type foo, and foo is defined as
Class Foo{
public int bar;
public double baz;
}
you can do get_foo().bar returning bar

Any language that allows a function to return an object/struct will support that... And languages like Ruby (where the () are optional) will make it exactly like you tiped (blah.number instead of blah().number).
Another way of avoiding the parentheses is using a property or an equivalent idiom... So C#, VB.NET and Python would also allow that.

If you want to make a new function out of an existing one, it's possible with lambda expressions. In C#, for example, it'd be var fooblah = (x => foo(x).blah); Obviously, if there's an overloading available in the language, you can't do it without giving a list of arguments.

Er...you mean, like a returning a class or a struct?
In C#
private class Blah
{
public string Data {get; set;}
public int Number {get; set;}
}
public Blah DoSomething()
{
return new Blah{Data="Data",Number=1};
}

Related

Interning strings in declarative programming

The following scenario shows an abstraction that seems to me to be impossible to implement declaratively.
Suppose that I want to create a Symbol object which allows you to create objects with strings that can be compared, like Symbol.for() in JavaScript. A simple implementation in JS might look like this:
function MySymbol(text){//Comparable symbol object class
this.text = text;
this.equals = function(other){//Method to compare to other MySymbol
return this.text == other.text;
}
}
I could easily write this in a declarative language like Haskell:
data MySymbol = MySymbol String
makeSymbol :: String -> MySymbol
makeSymbol s = MySymbol s
compareSymbol :: MySymbol -> MySymbol -> Bool
compareSymbol (MySymbol s1) (MySymbol s2) = s1 == s2
However, maybe in the future I want to improve efficiency by using a global registry without changing the interface to the MySymbol objects. (The user of my class doesn't need to know that I've changed it to use a registry)
For example, this is easily done in Javascript:
function MySymbol(text){
if (MySymbol.registry.has(text)){//check if symbol already in registry
this.id = MySymbol.registry.get(text);//get id
} else {
this.id = MySymbol.nextId++;
MySymbol.registry.set(text, this.id);//Add new symbol with nextId
}
this.equals = function(other){//To compare, simply compare ids
return this.id == other.id;
}
}
//Setup initial empty registry
MySymbol.registry = new Map();//A map from strings to numbers
MySymbol.nextId = 0;
However, it is impossible to create a mutable global registry in Haskell. (I can create a registry, but not without changing the interface to my functions.)
Specifically, these three possible Haskell solutions all have problems:
Force the user to pass a registry argument or equivalent, making the interface implementation dependent
Use some fancy Monad stuff like Haskell's Control.Monad.Random, which would require either foreseeing the optimization from the start or changing the interface (and is basically just adding the concept of state into your program and therefore breaks referential transparency etc.)
Have a slow implementation which might not be practical in a given application
None of these solutions allow me to sufficiently abstract away implementation from my Haskell interface.
So, my question is: Is there a way to implement this optimization to a Symbol object in Haskell (or any declarative language) without causing one of the three problems listed above,
and are there any other situations where an imperative language can express an abstraction (for example an optimization like above) that a declarative language can't?
The intern package shows how. As discussed by #luqui, it uses unsafePerformIO at a few key moments, and is careful to hide the identifiers produced during interning.

Is good to call function in other function parameter?

I suppose this:
public static string abc()
{
return "abc";
}
Is better to call this function in this way:
string call = abc();
Console.writeline(call);
Than this?
console.writeline(abc());
is there any reason to prefer one to the other?
Both are valid. However, out of experience I have concluded that the first option is more suitable for readability and ease of maintenance. I can't count how many times I have changed from the "compact" style to the first one as a help for a debugging session.
For example, this style makes it easy to check the correctness intermediate of an intermediate result:
string call = abc();
assert(!call.empty()); // Just an example.
Console.writeline(call);
Also, it helps to make the code more robust later, adding a conditional check before the subsequent action that checks call's value, for example if the design does not guarantee that the condition of the previous assert holds but you still need to check it.
string call = abc();
if (!call.empty())
{
Console.writeline(call);
}
Note also that with this style you will be able to easily inspect the value of call in your debugger.
Given your exact example (one parameter, value not used elsewhere, no side effects), it's just a matter of style. However, it gets more interesting if there are multiple parameters and the methods have side effects. For example:
int counter;
int Inc() { counter += 1; return counter }
void Foo(int a, int b) { Console.WriteLine(a + " " + b); }
void Bar()
{
Foo(Inc(), Inc());
}
What would you expect Foo to print here? Depending on the language there might not even be a predictable result. In this situation, assigning the values to a variable first should cause the compiler (depending on language) to evaluate the calls in a predictable order.
Actually I don't see a difference if you don't have any error checking.
This would make a difference
string call = abc();
# if call is not empty
{
Console.writeline(call);
}
The above method could avoid empty string being written.

What is the use of "use" keyword/method in groovy?

I read use keyword in Groovy. But could not come out with, for what it has been exactly been used. And i also come with category classes, under this topic,what is that too? And from, Groovy In Action
class StringCalculationCategory {
static def plus(String self, String operand) {
try {
return self.toInteger() + operand.toInteger()
} catch (NumberFormatException fallback) {
return (self << operand).toString()
}
}
}
use (StringCalculationCategory) {
assert 1 == '1' + '0'
assert 2 == '1' + '1'
assert 'x1' == 'x' + '1'
}
With the above code, can anyone say what is the use of use keyword in groovy? And also what the above code does?
See the Pimp My Library Pattern for what use does.
In your case it overloads the String.add(something) operator. If both Strings can be used as integers (toInteger() doesn't throw an exception), it returns the sum of those two numbers, otherwise it returns the concatenation of the Strings.
use is useful if you have a class you don't have the source code for (eg in a library) and you want to add new methods to that class.
By the way, this post in Dustin Marx's blog Inspired by Actual Events states:
The use "keyword" is actually NOT a keyword, but is a method on
Groovy's GDK extension of the Object class and is provided via
Object.use(Category, Closure). There are numerous other methods
provided on the Groovy GDK Object that provide convenient access to
functionality and might appear like language keywords or functions
because they don't need an object's name to proceed them. I tend not
to use variables in my Groovy scripts with these names (such as is,
println, and sleep) to avoid potential readability issues.
There are other similar "keywords" that are actually methods of the Object class, such as with. The Groovy JDK documentation has a list of such methods.
A very good illustration is groovy.time.TimeCategory. When used together with use() it allows for a very clean and readable date/time declarations.
Example:
use (TimeCategory) {
final now = new Date()
final threeMonthsAgo = now - 3.months
final nextWeek = now + 1.week
}

What's the name of this programming feature?

In some dynamic languages I have seen this kind of syntax:
myValue = if (this.IsValidObject)
{
UpdateGraph();
UpdateCount();
this.Name;
}
else
{
Debug.Log (Exceptions.UninitializedObject);
3;
}
Basically being able to return the last statement in a branch as the return value for a variable, not necessarily only for method returns, but they could be achieved as well.
What's the name of this feature?
Can this also be achieved in staticly typed languages such as C#? I know C# has ternary operator, but I mean using if statements, switch statements as shown above.
It is called "conditional-branches-are-expressions" or "death to the statement/expression divide".
See Conditional If Expressions:
Many languages support if expressions, which are similar to if statements, but return a value as a result. Thus, they are true expressions (which evaluate to a value), not statements (which just perform an action).
That is, if (expr) { ... } is an expression (could possible be an expression or a statement depending upon context) in the language grammar just as ?: is an expression in languages like C, C# or Java.
This form is common in functional programming languages (which eschew side-effects) -- however, it is not "functional programming" per se and exists in other language that accept/allow a "functional like syntax" while still utilizing heavy side-effects and other paradigms (e.g. Ruby).
Some languages like Perl allow this behavior to be simulated. That is, $x = eval { if (true) { "hello world!" } else { "goodbye" } }; print $x will display "hello world!" because the eval expression evaluates to the last value evaluated inside even though the if grammar production itself is not an expression. ($x = if ... is a syntax error in Perl).
Happy coding.
To answer your other question:
Can this also be achieved in staticly typed languages such as C#?
Is it a thing the language supports? No. Can it be achieved? Kind of.
C# --like C++, Java, and all that ilk-- has expressions and statements. Statements, like if-then and switch-case, don't return values and there fore can't be used as expressions. Also, as a slight aside, your example assigns myValue to either a string or an integer, which C# can't do because it is strongly typed. You'd either have to use object myValue and then accept the casting and boxing costs, use var myValue (which is still static typed, just inferred), or some other bizarre cleverness.
Anyway, so if if-then is a statement, how do you do that in C#? You'd have to build a method to accomplish the goal of if-then-else. You could use a static method as an extension to bools, to model the Smalltalk way of doing it:
public static T IfTrue(this bool value, Action doThen, Action doElse )
{
if(value)
return doThen();
else
return doElse();
}
To use this, you'd do something like
var myVal = (6 < 7).IfTrue(() => return "Less than", () => return "Greater than");
Disclaimer: I tested none of that, so it may not quite work due to typos, but I think the principle is correct.
The new IfTrue() function checks the boolean it is attached to and executes one of two delegates passed into it. They must have the same return type, and neither accepts arguments (use closures, so it won't matter).
Now, should you do that? No, almost certainly not. Its not the proper C# way of doing things so it's confusing, and its much less efficient than using an if-then. You're trading off something like 1 IL instruction for a complex mess of classes and method calls that .NET will build behind the scenes to support that.
It is a ternary conditional.
In C you can use, for example:
printf("Debug? %s\n", debug?"yes":"no");
Edited:
A compound statement list can be evaluated as a expression in C. The last statement should be a expression and the whole compound statement surrounded by braces.
For example:
#include <stdio.h>
int main(void)
{
int a=0, b=1;
a=({
printf("testing compound statement\n");
if(b==a)
printf("equals\n");
b+1;
});
printf("a=%d\n", a);
return 0;
}
So the name of the characteristic you are doing is assigning to a (local) variable a compound statement. Now I think this helps you a little bit more. For more, please visit this source:
http://www.chemie.fu-berlin.de/chemnet/use/info/gcc/gcc_8.html
Take care,
Beco.
PS. This example makes more sense in the context of your question:
a=({
int c;
if(b==a)
c=b+1;
else
c=a-1;
c;
});
In addition to returning the value of the last expression in a branch, it's likely (depending on the language) that myValue is being assigned to an anonymous function -- or in Smalltalk / Ruby, code blocks:
A block of code (an anonymous function) can be expressed as a literal value (which is an object, since all values are objects.)
In this case, since myValue is actually pointing to a function that gets invoked only when myValue is used, the language probably implements them as closures, which are originally a feature of functional languages.
Because closures are first-class functions with free variables, closures exist in C#. However, the implicit return does not occur; in C# they're simply anonymous delegates! Consider:
Func<Object> myValue = delegate()
{
if (this.IsValidObject)
{
UpdateGraph();
UpdateCount();
return this.Name;
}
else
{
Debug.Log (Exceptions.UninitializedObject);
return 3;
}
};
This can also be done in C# using lambda expressions:
Func<Object> myValue = () =>
{
if (this.IsValidObject) { ... }
else { ... }
};
I realize your question is asking about the implicit return value, but I am trying to illustrate that there is more than just "conditional branches are expressions" going on here.
Can this also be achieved in staticly
typed languages?
Sure, the types of the involved expressions can be statically and strictly checked. There seems to be nothing dependent on dynamic typing in the "if-as-expression" approach.
For example, Haskell--a strict statically typed language with a rich system of types:
$ ghci
Prelude> let x = if True then "a" else "b" in x
"a"
(the example expression could be simpler, I just wanted to reflect the assignment from your question, but the expression to demonstrate the feature could be simlpler:
Prelude> if True then "a" else "b"
"a"
.)

C# 4.0, Methods on the fly?

With the introduction of things like duck typing, I would love it if I compose object methods on the fly, besides extension methods. Anybody know if this is possible? I know that MS is worried about composing framework on the fly, but they seem to be dipping their toes in the water.
Update: Thanks to Pavel for clarifying. For example, say I return a new dynamic object from LINQ and would like to add some methods to it on the fly.
In light of the updated answer, you're actually not looking for "dynamic methods", so much so as "dynamic objects" - such that you may add new properties and methods to them at runtime. If that is correct, then in .NET 4.0, you can use ExpandoObject in conjunction with dynamic:
dynamic foo = new ExpandoObject();
foo.Bar = 123; // creates a new property on the fly
int x = foo.Bar; // 123
// add a new method (well, a delegate property, but it's callable as method)
foo.Baz = (Func<int, int, int>)
delegate(int x, int y)
{
return x + y;
};
foo.Baz(1, 2); // 3
You can have "dynamic methods" too, with expression trees, and once you obtain a delegate for such a method, you can also create a callable method-like property out of it on an ExpandoObject.
For use in LINQ queries, unfortunately, you cannot use object initializers with ExpandoObject; in the simplest case, the following will not compile:
var foo = new ExpandoObject { Bar = 123; }
The reason is that Bar in this case will be looked up statically as a property of ExpandoObject. You need the receiver to be dynamic for this feature to kick in, and there's no way to make it that inside an object initializer. As a workaround for use in LINQ, consider this helper extension method:
public static dynamic With(this ExpandoObject o, Action<dynamic> init)
{
init(o);
return o;
}
Now you can use it thus:
from x in xs
select new ExpandoObject().With(o => {
o.Foo = x;
o.Bar = (Func<int, int>)delegate(int y) { return x + y; };
});
Yes, there is: Generating Dynamic Methods with Expression Trees in Visual Studio 2010
This was already possible with the aid of DynamicMethod and/or MethodBuilder. Not sure if that counts for being "worried", as it has been around for a while now, though it requires a dynamic assembly in most scenarios (DynamicMethod can be used without, though).

Resources