Questions tagged [syntactic-sugar]
Syntactic sugar is a computer science term that refers to syntax within a programming language that is designed to make things easier to read or to express.
420
questions
0
votes
2
answers
50
views
Is there syntactic sugar for calling a function on each element of a list in JavaScript?
Let's say I had the following code:
let array = [1, 2, 3]
array.forEach(x => someFunc(x))
In Java, I know the second line could be simpler using Streams (at least for static methods), like so:
...
1
vote
2
answers
34
views
Write multiple setInterval() at once with the same second parameter
I'm making a clock UI that shows analog, digital, and date at the same time. I made a function for each case that requires setInterval(). I wanted to know if I could write them at once in case there ...
1
vote
2
answers
36
views
Syntactic sugar for (x != null && x.y != null)
Is there a syntactic sugar to write the following code in a better way?
if (x != null && x.y != null) {
...things that use x!.y
}
I could write something like
if (x?.y != null) {
......
1
vote
3
answers
159
views
Can I define a custom getter for a C# auto-implemented property (a.k.a. auto backing field)?
Note: I know how to accomplish this without using auto-implemented properties, but I'm wondering if C# has a built-in way to do this.
Let's say I have this simple example of an auto-implemented ...
0
votes
0
answers
40
views
Closed generic alias, that looks like Nullable
In C#, T? is equivalent to Nullable<T> when T : struct.
If there is custom generic class [or interface, or struct, etc.] Data<T>, then:
What can be done to refer Data<T> as T^ [or ~...
2
votes
0
answers
34
views
Shorthand to specify that a derived class implements all abstract methods?
I find that in some of my code which relies heavily on C++'s polymorphism features, I have a lot of repetitive method declarations.
struct Base
{
virtual void Foo () = 0;
virtual void Bar () = ...
2
votes
2
answers
108
views
impl Default sugar for large struct without derive
If I have a struct I need Default implemented on, if all the field's types have Default implemented themsevles, then I can use the derive macro, otherwise I need to implement Default manually. However,...
0
votes
1
answer
82
views
Partially constrained vector and arrays in VHDL
Is there some way to define an alias, function or subtype in a package to define syntactic sugar around constrained vector declaration?
I often declare port and signals in VHDL as std_logic_vector(N - ...
0
votes
0
answers
45
views
Does PHP have syntax sugar for `defined('X') && X`?
I often have to check the value of a constant, but it's not guaranteed that to exist. The typical way is if ( defined( 'X' ) && X ), but that gets annoying to type when a constant has a good, ...
1
vote
3
answers
88
views
Most elegant way to define helper variable in one-line expression
What's the best way to define a helper variable in a one-line expression in Python? I've found two: list comprehension and the "walrus" operator, but both can be somewhat clunky.
Example:
...
3
votes
1
answer
82
views
How to correctly desugar syntactic tree? - reduction of data structure definition / constructor disabling
I am developing a new language in Haskell and I run into a problem with syntactic tree T desugaring.
I have a set of functions f1, f2,... fn, which are simplifying the tree T from the "sugar"...
0
votes
0
answers
40
views
JavaScript syntactic sugar when incrementing/decrementing variable
LeetCode 680. Valid Palindrome II Easy
Given a string s, return true if the s can be palindrome after
deleting at most one character from it.
Can someone tell me why the first code below is much ...
2
votes
1
answer
98
views
structural induction of haskell
Hello everyone I want to ask if the following a definition of structural induction or not
init xs = take ( length xs - 1) xs
init :: [ a ] -> [ a ]
init ( x :[]) = []
init ( x : z : xs ) = x : ...
3
votes
0
answers
64
views
Is there a way to use syntactic sugar to build lists of existential types?
Consider a list-like type like this one:
{-# LANGUAGE ExistentialQuantification #-}
data ShowList = Nil | forall a. Show a => a :* ShowList
infixr 5 :*
myShowList :: ShowList
myShowList = 'x' :* (...
4
votes
2
answers
69
views
How do pattern match assignments in for comprehensions translate into monadic operations?
I am familiar with the concept that Scala's for comprehensions are just syntactic sugar for monadic operations (map, withFilter, foreach, and flatMap) and the desugaring is described in this popular ...
5
votes
2
answers
882
views
What is new without type in C#?
What is new without type in C#?
I met the following code at work:
throw new("some string goes here");
Is the new("some string goes here") a way to create strings in C# or is it ...
0
votes
0
answers
52
views
Xtext: define syntactic sugar for DSL
Is it possible to define some kind of rewrite rules for syntactic sugar for an Xtext DSL? (e.g. similar to how Spoofax handles it)
Let me demonstrate with an example: suppose we have a dummy ...
3
votes
1
answer
541
views
TypeScript: Getting the type of the property at keyof T
I'm having a bit of fun by playing with TypeScript and its typing system - it's nothing critical, but maybe some of you find this as interesting or fun as me.
Since I often find myself sorting arrays ...
8
votes
4
answers
184
views
Variable re-assign method result if not Nil
Is there idiomatic way of applying and assigning object variable method call, but only if it's defined (both method and the result)?
Like using safe call operator .? and defined-or operator //, and ...
4
votes
2
answers
109
views
Why is `x[i]` not equivalent to `x.__getitem__(x)`?
From the documentation:
x[i] is roughly equivalent to type(x).__getitem__(x, i).
What is the benefit of the above rather than having a seemingly simpler x.__getitem__(i)?
EDIT: Why is Python ...
0
votes
2
answers
138
views
range based for-loop on r-value
The following does not behave as i would like it too, as the destructor of Foo is called before the range-based for loop enters the body making the iterators invalid (msvc 2019).
Is there a way to &...
0
votes
1
answer
44
views
When use Syntactical form in react fragment then the editor text color will be changed. How to solve this problem
Here give the problem screenshot. How to solve this problem. have any away for solve this problem
[1]: https://i.stack.imgur.com/aHUvg.png reactFragment
1
vote
1
answer
114
views
At what stage in compiling does syntactic sugar generally become "desugared"
I'm curious as to how and when a compiler "desugars" syntactic sugar into it's final form. An example of syntatic sugar is a increment statement i++ turning into a assign statement i=i+1, or ...
2
votes
1
answer
535
views
Does Go support functional programming? [closed]
As in java8:
someList.stream().map(e->e.getXXX()).toList()
For example, I have a Student array/slice, and the struct Student contains properties like Id, Name, and so on.
I want to extract all Ids ...
1
vote
0
answers
58
views
How to convert compiler generated code into compilable C# code
I've written this app:
using System.Collections.Generic;
using System;
namespace Test
{
class Program
{
static void Main(string[] args)
{
var myClass = new ...
1
vote
1
answer
374
views
How to get ILSpy to show compiler generated code
I've written and built this app:
namespace Test
{
class Program
{
static void Main(string[] args)
{
var myClass = new MyClass();
foreach (var item ...
-2
votes
1
answer
49
views
Is it possible to avoid duplicate of equal arg-name and var-name in method call?
It it possible to replace
veryLongOption = ...
...
bar(arg1, arg2, veryLongOption = veryLongOption, anotherVeryLongOption = anotherVeryLongOption, more = more)
with something like this?
bar(arg1, ...
1
vote
1
answer
135
views
Can $obj.psObject.properties[$key].value be abbreviated
In order to get the value of a object's property whose name is stored in a variable, I use the following construct:
# Create object
$obj = new-object psObject -property @{ num = 42; txt = 'Hello world'...
-1
votes
1
answer
77
views
Omit using "this." all the time
I have pieces of code like
get ab(){
if(this.a == this.b) this.c = this.a.add(this.b);
if(this.d == this.b) this.d = this.a.add(this.b, this.bIdx).normalize();
return this....
0
votes
1
answer
389
views
choose a defined attribute in a nested object in jinja
I'm looking for a convenient, elegant way to display an attribute of nested object, choosing the first one which is defined.
Something like this :
from jinja2 import Template
o1 = { "a" : { ...
2
votes
0
answers
51
views
Python - short syntax for catching exceptions in expressions
Is there a short syntax for catching and processing exception within expressions. E.g if we have some complex expression eint(x) and another one eext(y) would be nice to do:
print(
eext(
...
1
vote
0
answers
39
views
Conditional line in handlebars.js with sugar
I am looking to get the following logic in Handlebars.js
the following line should appear in the output if foo is truthy
xxx.yyy.zzz = {{foo}}
no line should appear if foo is falsy
How can I do it?
...
0
votes
1
answer
75
views
dart gRPC: what the meaning of the function?
I'm new in flutter(dart) gRPC. I'm learing the tutorial given by https://grpc.io/docs/languages/dart/basics/. But I got confused about the dart syntax in this function.
Future<Feature> ...
0
votes
1
answer
554
views
Syntactic sugar for JavaScript Constructor [duplicate]
Let's say we have a simple constructor;
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
I'd rather use as follows.
function Person(firstName, ...
1
vote
2
answers
531
views
Shorthand or sugar for declaring multiple variables with same value?
I was wondering if there is a shorthand in ES6 or Babel to declare multiple variables with the same value, e.g. when using multiple refs in React:
const a = React.useRef();
const b = React.useRef();
...
0
votes
3
answers
162
views
How do you comprehend "std: :forward is just syntactic sugar"? Is that true?
How do you comprehend "std::forward is just syntactic sugar"? Is that true? I would appreciate that if you could explain the related code below in detail.
As per the documentation(https://gcc.gnu....
2
votes
2
answers
167
views
How do you make the use of std::variants more "palatable", syntax-wise?
This is motivated by an answer I gave a newbie user, where I suggested they use an std::variant instead of a union.
With a union, you may have something like the following:
struct Box {
struct ...
0
votes
0
answers
29
views
Is there null aware sum? [duplicate]
Can the last line be simplified more? Specifically is it possible not to repeat newItem and/or []?
import 'dart:math';
void main() {
var myList = [0, 1];
var rng = new Random();
var newItem = ...
2
votes
1
answer
189
views
How does the Prelude allow numeric literals for Nat?
In Type-Driven Development with Idris ch. 4, they say
The Prelude also defines functions and notation to allow Nat to be used like any other numeric type, so rather than writing S (S (S (S Z))), ...
1
vote
0
answers
168
views
DAX syntax sugar examples
I just came accross article on syntax sugar in DAX - https://exceleratorbi.com.au/simple-filters-and-syntax-sugar-in-dax/
1.
Total Sales Syntax Sugar = SUM(Sales[ExtendedAmount])
Total Sales Full ...
0
votes
1
answer
48
views
Alternative of "??" for non nullable types (e.g. when looking up dictionary keys) [duplicate]
It's very convenient using inline sugar like that: obj?.func(); and obj ?? anotherObj
But I'm trying to find an alternative to the same approach in case I want to pull data from a dictionary without ...
0
votes
1
answer
192
views
Swift - How to I define a special method for my class that returns a string representation of its object
In python if you want to define a string representation of an object you can do the following:
class Person:
def __init__(self, first, last, age):
self.first = first
self.last = ...
0
votes
1
answer
53
views
Shorthand form of generics that can be undefined
I know that it is possible to do somethink like this in TypeScript
variable: number | undefined;
variable?: number; // shorthand version
My question is if it is possible to do something similar when ...
7
votes
2
answers
4k
views
Python multiplication equivalent to integer division
In python using // for division forces the result to be an integer. Is there an equivalent for multiplication?
For example, assume I have an integer W which I scale by a float f. It could be nice to ...
1
vote
1
answer
499
views
Appending item to list within a list comprehension using if/else and for loop
I already know how to append a value depending on a for with an if loop but I want to know if there is an optimized way to do it.
Here is the solution:
column=[]
for i in range(movies.shape[1]):
...
1
vote
2
answers
80
views
Non-equal operator syntactic sugar on a nullable class?
I was checking up the Unity API documentation and stumbled upon this example code block:
using UnityEngine;
public class Example : MonoBehaviour
{
public GameObject target;
void Reset()
...
2
votes
1
answer
165
views
Does IO monad become strict when bang pattern is used?
I expect the following code snippet:
main = do
let !x = [2,3,5,2,3,5,6,7,1,3,0,1]
begin <- getCPUTime
let !rx = reverse x
end <- getCPUTime
putStrLn $ "Calculation time: " ++...
0
votes
1
answer
44
views
Name of expression?
I wrote some code a while ago, but I forgot the name of the syntactic sugar I used and can't find it anymore. I guess it had something with nullable in its name but I am not entirely sure.
That is ...
2
votes
2
answers
279
views
How to implement universal switch/case, which can work for general C++ types as well and syntactically similar?
In C/C++, switch/case compares only an integral type with a compile time constants. It's not possible to use them to compare user/library defined types like std::string with runtime values. Why the ...
0
votes
2
answers
168
views
`error: assignment to expression with array type` when trying to set struct member
I'm sure this has been asked before, but I can't find it.
Consider:
#include <stdlib.h>
struct Image {
char* name;
float transform[6];
};
int main() {
float transform[6] = {0,0,0,...