Is there an accepted "standard" way to format lambda-expressions in C++ >= 11 ? Especially when put in generic algorithms for instance.
For instance :
1)
auto it = std::find_if(myVec.begin(),
myVec.end(),
[id = 42] (const Element& e)
{ return e.id() == id;});
Or
2)
auto it = std::find_if(myVec.begin(),
myVec.end(),
[id = 42]
(const Element& e)
{ return e.id() == id;});
Or
3)
auto it = std::find_if(myVec.begin(),
myVec.end(),
[id = 42] (const Element& e)
{
return e.id() == id;
});
Or 4)
auto it = std::find_if(myVec.begin(),
myVec.end(),
[id = 42] (const Element& e)
{
return e.id() == id;
});
Or any other combination of carriage returns, spaces, tabs...
Note : I use Allman style in my code, so ideally it would be "fitting in the same style".
I have always preferred to endow relative levels of indent with their own semantic value and vertically align a closing delimiter with the line that contains its matching opening delimiter. This makes complex statements (like those with lambda expressions as arguments) easier to read:
auto it = std::find_if(
myVec.begin(),
myVec.end(),
[id = 42] (const Element& e){ return e.id() == id;}
);
or (if, for example, the lambda body was too long for one line)
auto it = std::find_if(
myVec.begin(),
myVec.end(),
[id = 42] (const Element& e){
return e.id() == id;
}
);
There is no de jure standard way yet. However, you can easily adopt your favorite C++ style. For example, an improvised Allman style:
std::for_each(
m_pages[i].begin() + m_pageSize,
m_pages[i].end(),
[this, i, &insertPlace](const CItemRef& item)
{
if(!item->IsOK())
{
insertPlace = m_pages[i+1].insert(insertPlace, item);
}
}
);
It is your number (3). Number (2) is usable for one-liners.
In my humble opinion, (1) and (4) break the spirit of indenting (they do not emphasize the logical structure of the whole lambda block). I would not use them.
Personally, I don't like wasted whitespace on the left, so I like to put my multiple arguments with one extra level of standard indentation, starting on the next line:
auto it = std::find_if(
myVec.begin(),
myVec.end(),
[id = 42](const Element& e) { return e.id() == id; }
);
Or, for longer lambdas:
auto it = std::find_if(
myVec.begin(),
myVec.end(),
[id = 42](const Element& e) {
return e.id() == id;
}
);
So, regardless of function name length, my function arguments start at the same indent (in a scope) and this way there is more room for your lambda on the right.
Related
I want a list.forEach and if in forEach and when this if return true I want to break this code like that
list.forEach((element){
if(element == "a"){
break
}
})
but it didn't help.
Rewrite your forEach call to a for-each loop:
for (final element in list) {
if (element == "a") {
break;
}
}
Real answer on a real question about how to break forEach in if.
void main() {
final seq1 = [0, 1, 2];
final result = <int>[];
try {
seq1.forEach((e) {
if (e == 2) throw 'Stop this immediately';
result.add(e);
});
} catch (e) {
// What? Something happened?
}
print(result);
}
Result:
[0, 1]
Not the most practical option, but it works.
That is, fully functional, for your case (break forEach).
The answer fully answers your question.
Do you have any other question?
I came across a question in an interview. I tried solving it but could not come up with a solution. Question is:
[Edited]
First Part: You are given two expressions with only "+" operator, check if given two expressions are mathematically equivalent.
For eg "A+B+C" is equivalent to "A+(B+C)".
Second Part : You are given two expressions with only "+" and "-" operators, check if given two expressions are mathematically equivalent.
For eg "A+B-C" is equivalent to "A-(-B+C)".
My thought process : I was thinking in terms of building an expression tree out of the given expressions and look for some kind of similarity. But I am unable to come up with a good way of checking if two expression trees are some way same or not.
Can some one help me on this :) Thanks in advance !
As long as the operations are commutative, the solution I'd propose is distribute parenthetic operations and then sort terms by 'variable', then run an aggregator across them and you should get a string of factors and symbols. Then just check the set of factors.
Aggregate variable counts until encountering an opening brace, treating subtraction as addition of the negated variable. Handle sub-expressions recursively.
The content of sub-expressions can be directly aggregated into the counts, you just need to take the sign into account properly -- there is no need to create an actual expression tree for this task. The TreeMap used in the code is just a sorted map implementation in the JDK.
The code takes advantage of the fact that the current position is part of the Reader state, so we can easily continue parsing after the closing bracket of the recursive call without needing to hand this information back to the caller explicitly somehow.
Implementation in Java (untested):
class Expression {
// Count for each variable name
Map<String, Integer> counts = new TreeMap<>();
Expression(Srring s) throws IOException {
this(new StringReader(s));
}
Expression(Reader reader) throws IOException {
int sign = 1;
while (true) {
int token = reader.read();
switch (token) {
case -1: // Eof
case ')':
return;
case '(':
add(sign, new Expression(reader));
sign = 1;
break;
case '+':
break;
case '-':
sign = -sign;
break;
default:
add(sign, String.valueOf((char) token));
sign = 1;
break;
}
}
}
void add(int factor, String variable) {
int count = counts.containsKey(variable) ? counts.get(variable) : 0;
counts.put(count + factor, variable);
}
void add(int sign, Expression expr) {
for (Map.Entry<String,Integer> entry : expr.counts.entrySet()) {
add(sign * entry.getVaue(), entry.getKey());
}
}
void equals(Object o) {
return (o instanceof Expression)
&& ((Expression) o).counts.equals(counts);
}
// Not needed for the task, just added for illustration purposes.
String toString() {
StringBuilder sb = new StringBuilder();
for (Map.Entry<String,Integer> entry : expr.counts.entrySet()) {
if (sb.length() > 0) {
sb.append(" + ");
}
sb.append(entry.getValue()); // count
sb.append(entry.getKey()); // variable name
}
return sb.toString();
}
}
Compare with
new Expression("A+B-C").equals(new Expression("A-(-B+C)"))
P.S: Added a toString() method to illustrate the data structure better.
Should print 1A + 1B + -1C for the example.
P.P.P.P.S.: Fixes, simplification, better explanation.
You can parse the expressions from left to right and reduce them to a canonical form for comparison in a straightforward way; the only complication is that when you encounter a closing bracket, you need to know whether its associated opening bracket had a plus or minus in front of it; you can use a stack for that; e.g.:
function Dictionary() {
this.d = [];
}
Dictionary.prototype.add = function(key, value) {
if (!this.d.hasOwnProperty(key)) this.d[key] = value;
else this.d[key] += value;
}
Dictionary.prototype.compare = function(other) {
for (var key in this.d) {
if (!other.d.hasOwnProperty(key) || other.d[key] != this.d[key]) return false;
}
return this.d.length == other.d.length;
}
function canonize(expression) {
var tokens = expression.split('');
var variables = new Dictionary();
var sign_stack = [];
var total_sign = 1;
var current_sign = 1;
for (var i in tokens) {
switch(tokens[i]) {
case '(' : {
sign_stack.push(current_sign);
total_sign *= current_sign;
current_sign = 1;
break;
}
case ')' : {
total_sign *= sign_stack.pop();
break;
}
case '+' : {
current_sign = 1;
break;
}
case '-' : {
current_sign = -1;
break;
}
case ' ' : {
break;
}
default : {
variables.add(tokens[i], current_sign * total_sign);
}
}
}
return variables;
}
var a = canonize("A + B + (A - (A + C - B) - B) - C");
var b = canonize("-C - (-A - (B + (-C)))");
document.write(a.compare(b));
I have an IEnumerable and a predicate (Func) and I am writing a method that shall return a value if only one instance in the list matches the predicate. If the criteria is matched by none, then none was found. If the criteria is matched by many instances, then the predicate was insufficient to successfully identify the desired record. Both cases should return null.
What is the recommended way to express this in LINQ that does not result in multiple enumerations of the list?
The LINQ operator SingleOrDefault will throw an exception if multiple instances are found.
The LINQ operator FirstOrDefault will return the first even when multiple was found.
MyList.Where(predicate).Skip(1).Any()
...will check for ambiguity, but will not retain the desired record.
It seems that my best move is to grab the Enumerator from MyList.Where(predicate) and retain the first instance if accessing the next item fails, but it seems slightly verbose.
Am I missing something obvious?
The "slightly verbose" option seems reasonable to me, and can easily be isolated into a single extension method:
// TODO: Come up with a better name :)
public static T SingleOrDefaultOnMultiple<T>(this IEnumerable<T> source)
{
// TODO: Validate source is non-null
using (var iterator = source.GetEnumerator())
{
if (!iterator.MoveNext())
{
return default(T);
}
T first = iterator.Current;
return iterator.MoveNext() ? default(T) : first;
}
}
Update: Here is a more general approach which might be more reusable.
public static IEnumerable<TSource> TakeIfCountBetween<TSource>(this IEnumerable<TSource> source, int minCount, int maxCount, int? maxTake = null)
{
if (source == null)
throw new ArgumentNullException("source");
if (minCount <= 0 || minCount > maxCount)
throw new ArgumentException("minCount must be greater 0 and less than or equal maxCount", "minCount");
if (maxCount <= 0)
throw new ArgumentException("maxCount must be greater 0", "maxCount");
int take = maxTake ?? maxCount;
if (take > maxCount)
throw new ArgumentException("maxTake must be lower or equal maxCount", "maxTake");
if (take < minCount)
throw new ArgumentException("maxTake must be greater or equal minCount", "maxTake");
int count = 0;
ICollection objCol;
ICollection<TSource> genCol = source as ICollection<TSource>;
if (genCol != null)
{
count = genCol.Count;
}
else if ((objCol = source as ICollection) != null)
{
count = objCol.Count;
}
else
{
using (IEnumerator<TSource> enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext() && ++count < maxCount);
}
}
bool valid = count >= minCount && count <= maxCount;
if (valid)
return source.Take(take);
else
return Enumerable.Empty<TSource>();
}
Usage:
var list = new List<string> { "A", "B", "C", "E", "E", "F" };
IEnumerable<string> result = list
.Where(s => s == "A")
.TakeIfCountBetween(1, 1);
Console.Write(string.Join(",", result)); // or result.First()
In my search for a expression parser, I found the Dynamic LINQ API. I want to use this API for letting the end user specify some criteria for validation of the business objects.
So my first attempt to use the library succeeds with the following Unit test
var x = Expression.Parameter(typeof(int), "x");
var list = Expression.Parameter(typeof(List<int>), "list");
var e = DynamicExpression.ParseLambda(new[] { x, list }, null, "list.Any(it == x)");
var compiledExpression = e.Compile();
var myList = new List<int> { 24, 46, 67, 78 };
Assert.AreEqual(false, compiledExpression.DynamicInvoke(2, myList));
Assert.AreEqual(true, compiledExpression.DynamicInvoke(24, myList));
However I want to have a slightly more complex syntax as I want to change this
list.Any(it == x) // OK
into
list.Any(i => i == x) // Raises error: No property or field 'i' exists in type 'int'
The second syntax would however allow me to nest lambda's (which is my ultimate goal) like so:
list1.All(i => list2.Any(j => j == i))
Anyone know how to adjust Dynamic.cs to support this syntax?
After some hours of debugging I found the solution myself.
The following unit test succeeds now:
var list1 = Expression.Parameter(typeof(List<int>), "list1");
var list2 = Expression.Parameter(typeof(List<int>), "list2");
var e = DynamicExpression.ParseLambda(new[] { list1, list2 }, null, "list2.All(i => list1.Any(j => j == i))");
var compiledExpression = e.Compile();
var myList1 = new List<int> { 24, 46, 67, 78 };
var myList2 = new List<int> { 46 };
var myList3 = new List<int> { 8 };
Assert.AreEqual(true, compiledExpression.DynamicInvoke(myList1, myList2));
Assert.AreEqual(false, compiledExpression.DynamicInvoke(myList1, myList3));
The changes I have applied to the example Dynamic.cs file:
1) Extend the enum TokenId with the member 'Lambda'
2) Add an IDictionary named internals to class ExpressionParser. Initialize it in the ExpressionParser constructor
3) Replace (starting on line 971)
if (symbols.TryGetValue(token.text, out value) ||
externals != null && externals.TryGetValue(token.text, out value)) {
with
if (symbols.TryGetValue(token.text, out value) ||
externals != null && externals.TryGetValue(token.text, out value) ||
internals.TryGetValue(token.text, out value)) {
4) Replace (starting on line 1151)
if (member == null)
throw ParseError(errorPos, Res.UnknownPropertyOrField,
id, GetTypeName(type));
with
if (member == null)
{
if(token.id == TokenId.Lambda && it.Type == type)
{
// This might be an internal variable for use within a lambda expression, so store it as such
internals.Add(id, it);
NextToken();
var right = ParseExpression();
return right;
}
else
{
throw ParseError(errorPos, Res.UnknownPropertyOrField,
id, GetTypeName(type));
}
}
5) Replace (starting on line 1838)
case '=':
NextChar();
if (ch == '=') {
NextChar();
t = TokenId.DoubleEqual;
}
else {
t = TokenId.Equal;
}
break;
with
case '=':
NextChar();
if (ch == '=') {
NextChar();
t = TokenId.DoubleEqual;
}
else if(ch == '>')
{
NextChar();
t = TokenId.Lambda;
}
else {
t = TokenId.Equal;
}
break;
Before someone shouts out the answer, please read the question through.
What is the purpose of the method in .NET 4.0's ExpressionVisitor:
public static ReadOnlyCollection<T> Visit<T>(ReadOnlyCollection<T> nodes, Func<T, T> elementVisitor)
My first guess as to the purpose of this method was that it would visit each node in each tree specified by the nodes parameter and rewrite the tree using the result of the elementVisitor function.
This does not appear to be the case. Actually this method appears to do a little more than nothing, unless I'm missing something here, which I strongly suspect I am...
I tried to use this method in my code and when things didn't work out as expected, I reflectored the method and found:
public static ReadOnlyCollection<T> Visit<T>(ReadOnlyCollection<T> nodes, Func<T, T> elementVisitor)
{
T[] list = null;
int index = 0;
int count = nodes.Count;
while (index < count)
{
T objA = elementVisitor(nodes[index]);
if (list != null)
{
list[index] = objA;
}
else if (!object.ReferenceEquals(objA, nodes[index]))
{
list = new T[count];
for (int i = 0; i < index; i++)
{
list[i] = nodes[i];
}
list[index] = objA;
}
index++;
}
if (list == null)
{
return nodes;
}
return new TrueReadOnlyCollection<T>(list);
}
So where would someone actually go about using this method? What am I missing here?
Thanks.
It looks to me like a convenience method to apply an aribitrary transform function to an expression tree, and return the resulting transformed tree, or the original tree if there is no change.
I can't see how this is any different of a pattern that a standard expression visitor, other than except for using a visitor type, it uses a function.
As for usage:
Expression<Func<int, int, int>> addLambdaExpression= (a, b) => a + b;
// Change add to subtract
Func<Expression, Expression> changeToSubtract = e =>
{
if (e is BinaryExpression)
{
return Expression.Subtract((e as BinaryExpression).Left,
(e as BinaryExpression).Right);
}
else
{
return e;
}
};
var nodes = new Expression[] { addLambdaExpression.Body }.ToList().AsReadOnly();
var subtractExpression = ExpressionVisitor.Visit(nodes, changeToSubtract);
You don't explain how you expected it to behave and why therefore you think it does little more than nothing.