What is the equivalent of with from Pascal language in C/C++ language?
A with statement is a shorthand for referencing the fields of a record or the fields, properties, and methods of an object.
Example
With (Object) do
begin
Width:=200;
Height:=300;
end;
Is Equivalent with:
Object.Width=200;
Object.Height=200;
I don't believe that there is any direct equivalent to that statement in c/c++.
If your objective is to avoid repeatedly typing "Object", then I suppose you could use a reference to map it to a shorter name, such as:
ClassName& o = Object;
o.prop1 = "meep";
o.prop2 = "moop";
But I would personally only use this in cases where "Object" is a complex expression. E.g.:
ClassName& o = something.getSomeOtherThing().getSomeThirdThing();
o.prop1 = "meep";
o.prop2 = "moop";
Related
I'm trying to better understand reasoning behind the value types.
Does value/reference types in Nim works same way as in Swift?
yes, value and reference types do work in Nim as in Swift and other low-level programming languages like C#, C++, Rust. By that I mean that they follow these semantics with respect to copy:
Value semantics means that the copy owns its memory and lives separately from the copied.
Reference semantics means that the copy and the copied refer to the same underlying memory location.
(taken from this forum answer).
As an example, I translate this swift blog post to nim (playground):
# port of https://developer.apple.com/swift/blog/?id=10 to Nim
## Example of Value type
type S = object
data: int # I cannot say the default of data is -1. Nim does not have (yet) custom initialization, see accepted RFC https://github.com/nim-lang/RFCs/issues/252
var a = S()
var b = a
a.data = 42
echo (a, b) # ((data: 42), (data: 0))
## Example of Reference type
type C = ref object
data: int
func `$`(c: C): string = "C(data: " & $(c.data) & ")" # there is no default $ for ref objects as there is for objects
var x = C()
var y = x
x.data = 42
echo (x, y) # (C(data: 42), C(data: 42))
Note that:
Nim does not have a copy-on-write mechanism for value types as in Swift (but you can build your own CoW type)
Nim does not have a === operator like Swift (see this discussion).
What are the uses of the underscore in Haxe?
I see that I can use it in loops and in array and map comprehensions when I don't care what the counter is, for example:
var a = [for (_ in 0...5) Math.random()]; // 5 random nums
Are there any other places where it's commonly used?
It's generally to denote values that indeed exist, but are not used in the code. Other uses would include:
function arguments that are not used:
button.addListener('click', function (_) trace('clicked!'));
enum constructor arguments that are ignored:
var o = haxe.ds.Option.Some(5);
switch o {
case None: trace('no value');
case Some(_): trace('some value');
}
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"
.)
What languages provide the use of object literals? (Or in what languages could you easily emulate them?) Can you give a code example?
Starting with the obvious javascript snippet:
var someObj = {
someProperty: 123,
someFunction: function() {
alert('hello!');
}
};
Checkout C# anonymous types
var Customer = new
{
Company = "AgileApps",
Website = "http://www.agileapps.co.uk",
Name = "Big Al",
Entered = DateTime.Now
};
If you replace object by "term," then Prolog does this naturally (in fact, there's no other way to construct an object). Here's an example featuring binary trees:
% find a node in List with a nil left child and call its rightmost grandchild X
member(node(nil,node(_,X)), List).
Lisp and Scheme also have some pretty advances features in this area, particularly quoting and semiquoting:
;; construct right-leaning binary tree with x as the rightmost grandchild
`(nil . (nil . ,x))
Practically all functional programming languages have copied this in some form.
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).