TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Ask HN: Your favorite syntactic sugar from any language?

32 pointsby davegaueralmost 7 years ago
Most programming languages I&#x27;ve encountered, no matter how otherwise unappealing, have at least one syntactic feature that makes them really pleasurable for at least <i>some</i> type of task.<p>Some things I miss when I don&#x27;t have them are:<p>* &quot;=~&quot; for regex matching (as in Perl and Ruby)<p>* &quot;{foo:[&#x27;bar&#x27;,&#x27;baz&#x27;]}&quot; for quick data structures (as in JavaScript)<p>* &quot;for f in *; do echo $f; done&quot; for looping over a &#x27;glob&#x27; of files (as in Bash)<p>What&#x27;s your favorite bit of sugar?

42 comments

jwilkalmost 7 years ago
Syntactic sugar is not another name for &quot;really cool syntax&quot;. They are non-essential constructs, which could be removed without much effect on the language, except for readability.<p>&quot;=~&quot; in Perl and globbing in shell are not syntactic sugar. They are fundamental parts of the languages.
评论 #17324535 未加载
评论 #17324727 未加载
artemisynaalmost 7 years ago
Haskell has way too much syntactic sugar some of the time, but I really appreciate its anonymous function syntax.<p>If I need a quick-and-dirty map over a list of something, a<p><pre><code> (\x -&gt; x + 1) a </code></pre> is much nicer than a<p><pre><code> std::for_each(a.start(), a.end(), [](float x) { return x + 1; } &#x2F;&#x2F; end of lambda expression ) </code></pre> or whatnot that I have to do in C++.
评论 #17324562 未加载
评论 #17324481 未加载
评论 #17325369 未加载
kjeetgillalmost 7 years ago
I love love love almost everything about Python&#x27;s syntax.<p>Slices that support negative indexes. List and dictionary comprehensions are amazing: { (X,Y): X<i></i>2 + Y for X in range(10) for Y in someiter if Y &gt; 5} I love that they become generators when you use () instead of []. Pure genius. Generators from a function containing yield or yield from equally beautiful. % for string interpolation was so good they had to bring it back. Tripple quotes using &quot;&quot;&quot; and &#x27;&#x27;&#x27; are hard to beat. Using func(<i>list) to unpack a list into a functions arguments. Or func(</i><i>dict) to unpack a map by name. Using </i>args and <i></i>kwargs to implimentaions variadic functions. I love indentation based code blocks. The way &#x27;and&#x27; and &#x27;or&#x27; can return values is so much better than a ?: terinary. I think I dumped a third of the Python spec there.<p>I could use a multi-line lambda but it&#x27;s not a huge omission. Pipelines like bash | pipe or F# |&gt; would be welcome.<p>go&#x27;s select statement is also subtle but smart. Doing multiple waits in one thread is tricky to impossible in most any other language.<p>Built in regex like perl is always nice when you have it.<p>I&#x27;m sure I missed something gushing over Python, but tapping this out over the phone if already killing my thumb.<p>Java desperately needs groovys&#x27;s safe navigation operator a?.getB()?.getC(). It&#x27;s like a normal method call but returns null if the receiver is null instead of throwing an NPE.
评论 #17324537 未加载
评论 #17327042 未加载
评论 #17324585 未加载
rehemiaualmost 7 years ago
Pipeline operator ( |&gt; ) in functional programming languages (Elixir, F#, Elm)
hprotagonistalmost 7 years ago
I really like C#&#x27;s =&gt; operator, especially in the context of expression-body members.<p><pre><code> public override string ToString() =&gt; $&quot;{fname} {lname}&quot;.Trim(); </code></pre> I am overjoyed with newer python&#x27;s f-strings.<p><pre><code> foo = 5 bar = 4.5005 print(f&#x27;foo is {foo} and the first bit of bar is {bar:0.2f}&#x27;) </code></pre> I really like python&#x27;s * and <i></i><i></i>* unpacking, and especially that you can do it in the middle with throwaways:<p><pre><code> first, *_, last = function_that_returns_ten_things() </code></pre> or for building kwarg-only classes from dicts:<p><pre><code> foo = {&#x27;x&#x27;:5,&#x27;y&#x27;:6} bar = Point(**foo)</code></pre>
AnimalMuppetalmost 7 years ago
The defaults in Perl, especially the default variable.<p>(For those not familiar: $_ is the default variable in Perl. Many operations use this variable if you don&#x27;t specify one. You can use $_ like &quot;it&quot; in English: &quot;Read in a line of input. If it ends in a newline...&quot; In most languages, you would have to deal with &quot;Read it into where?&quot; and &quot;If <i>what</i> ends in a newline?&quot; But in Perl, if you don&#x27;t specify where to read the line to, it goes into $_, and if you don&#x27;t specify what you want to see if it ends in a newline, it checks $_, and so on...)
评论 #17324634 未加载
fvdessenalmost 7 years ago
I really like python&#x27;s array slices, a[5:] b[2:3], and list comprehensions, [x * 2 for x in array if x &gt; 0]
评论 #17324376 未加载
评论 #17324335 未加载
评论 #17324738 未加载
LordHeinialmost 7 years ago
Beying somewhat of a functinal fanboy i really like Scalas (and oder functinal languages) point free style.<p>Instead of:<p>listOfThings.foreach(x =&gt; println(x))<p>You can just type<p>listOfThings foreach println<p>Type inference is also great.<p>Scala in general has lots and lots of syntactic sugar, which is kind of the point of Scala.<p>Honroable mention:<p>Rubys &amp;. operator<p>instead of<p>y = x.nil? ? nil : x.foo<p>y = x&amp;.foo<p>Or just use a language which has some sort of null savety like Option types.
ioddlyalmost 7 years ago
Scheme&#x27;s expression comments are really quite handy, but only possible to implement in languages where everything is an expression.<p>For those not familiar, you can have the reader just discard an expression, so like (list 1 #;2 3) becomes (list 1 3), but you can handily comment out a giant function call or if expression or something while you work on it.<p>Scheme&#x27;s nestable multiline comments are also nice. I&#x27;m not sure which language was first, but I think more languages are getting them now (Kotlin has them IIRC).
评论 #17330932 未加载
christophilusalmost 7 years ago
For me, it&#x27;s Clojure&#x27;s threading macros. They&#x27;re like the `|&gt;` operator on steroids. Also from Clojure, the ability to use maps and keywords as functions in a lot of cases, such as: `(map :hello [{:hello &quot;world&quot;}]) ; [&quot;world&quot;]` and `({:hello &quot;world&quot;} :hello) ; &quot;world&quot;` It comes in really handy more often than I would have thought.
Pete_Dalmost 7 years ago
Common Lisp&#x27;s LOOP macro is a fearsome beast.<p><a href="http:&#x2F;&#x2F;www.ai.sri.com&#x2F;~pkarp&#x2F;loop.html" rel="nofollow">http:&#x2F;&#x2F;www.ai.sri.com&#x2F;~pkarp&#x2F;loop.html</a><p><a href="http:&#x2F;&#x2F;www.lispworks.com&#x2F;documentation&#x2F;HyperSpec&#x2F;Body&#x2F;m_loop.htm" rel="nofollow">http:&#x2F;&#x2F;www.lispworks.com&#x2F;documentation&#x2F;HyperSpec&#x2F;Body&#x2F;m_loop...</a>
kendallparkalmost 7 years ago
Ruby inline conditionals. They read like English. Short and sweet.<p><pre><code> if condition? return end if !i_probably_shouldnt? do_something end </code></pre> Becomes:<p><pre><code> return if condition? do_something unless i_probably_shouldnt?</code></pre>
评论 #17324564 未加载
评论 #17324695 未加载
himomalmost 7 years ago
Technically, any Turing-complete language can be mapped to any other Turing complete language, so it’s possible to have non-trivial syntatic sugar do anything. (Use brainfuck as IR, lol.) &gt;:) But yeah, SS is more like:<p><pre><code> ++x; &#x2F;&#x2F; x = x + 1 </code></pre> Nifty syntax<p><pre><code> &amp;:foo Ruby method name to callable syntax foo&amp;.bar Ruby check nil before calling bar foo?.bar Swift optional presence check if(x = foo!.bar!) { x.something() } foo ?? bar Swift nil-coalescing foo || bar Ruby nil-coalescing &lt;&lt;1,4,8,45&gt;&gt; Erlang bit syntax (binary literals), with typing and endianess 5b432140 Erlang arbitrary base literals List comprehensions Erlang, Python, Binary comprehensions in Erlang 2&gt; Pixels = &lt;&lt;213,45,132,64,76,32,76,0,0,234,32,15&gt;&gt;. &lt;&lt;213,45,132,64,76,32,76,0,0,234,32,15&gt;&gt; 3&gt; RGB = [ {R,G,B} || &lt;&lt;R:8,G:8,B:8&gt;&gt; &lt;= Pixels ]. [{213,45,132},{64,76,32},{76,0,0},{234,32,15}] -- from LearnYouSomeErlang Show anon fn’s in many languages using utf8 λ. Swift property lifecycle callbacks</code></pre>
Doxinalmost 7 years ago
I&#x27;m absolutely positively in love with &quot;Universal function call syntax&quot; from D, it makes the following:<p><pre><code> foo.bar(baz) </code></pre> compile to the following if foo has no property bar:<p><pre><code> bar(foo, baz) </code></pre> It allows you to trivially extend classes from libraries without meddling with their code or breaking other code using the library. e.g. if you define:<p><pre><code> string helloWorldize(string input){ return &quot;Hello, &quot;~input; } </code></pre> You can then do this anywhere &quot;helloWorldize&quot; is in scope:<p><pre><code> &quot;bob&quot;.helloWorldize(); </code></pre> And because of the strong type system and smart compiler you&#x27;ll never run into situations where you call helloWorldize when you don&#x27;t mean to.
city41almost 7 years ago
I miss CoffeeScript&#x27;s existential operator now that all my projects are standard ES6.<p><a href="https:&#x2F;&#x2F;coderwall.com&#x2F;p&#x2F;jwzppw&#x2F;the-existential-operator-in-coffeescript" rel="nofollow">https:&#x2F;&#x2F;coderwall.com&#x2F;p&#x2F;jwzppw&#x2F;the-existential-operator-in-c...</a>
评论 #17326781 未加载
ralstonalmost 7 years ago
Python 3.5+<p><pre><code> &gt;&gt;&gt; first = {&quot;a&quot;: 1} &gt;&gt;&gt; second = {&quot;b&quot;: 2} &gt;&gt;&gt; merged = {**x, **y} &gt;&gt;&gt; print(merged) {&quot;a&quot;: 1, &quot;b&quot;: 2}</code></pre>
评论 #17324438 未加载
评论 #17324436 未加载
frflalmost 7 years ago
Sorry, this comment will not really benefit the matter at hand, but I&#x27;d like to share a relevant quote I quite enjoyed when I first read it<p>&gt; Syntactic sugar causes cancer of the semicolon. - Alan Perlis
snarfybarfyalmost 7 years ago
Multiline strings aka &#x27;here documents&#x27; in most Shells.<p>Rich datastructure literals in Clojure for sets #{&#x27;foo&#x27;}, maps {:a 1, :b 2}, lists (1,2,3) vectors [1, 2, 3]<p>The serialization format EDN is basically JSON on steroids.<p><a href="https:&#x2F;&#x2F;github.com&#x2F;edn-format&#x2F;edn" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;edn-format&#x2F;edn</a>
laogaialmost 7 years ago
Ruby&#x27;s &amp; operator.<p>At first I hated it because of how incomprehensible it was to someone coming from seemingly every other language, but I&#x27;ve started to use it more and more and wishing it existed in other languages.<p>It&#x27;s especially useful for when the variable access is many characters. e.g. `if hackerNews.frontPage.votingCircleExists:` with nil checks is `if hackerNews &amp;&amp; hackerNews.frontPage &amp;&amp; hackerNews.frontPage.votingCircleExists`<p>and with &amp; operator is: `if hackerNews&amp;.frontPage&amp;.votingCircleExists`.
评论 #17324539 未加载
评论 #17324507 未加载
ezekgalmost 7 years ago
Python&#x2F;Ruby&#x27;s kwargs, JavaScript&#x27;s destructuring syntax, Python list comprehensions, Ruby&#x27;s array push &lt;&lt; method, ranges, and literal array expressions
nunezalmost 7 years ago
Ruby’s question marks for Boolean functions and exclamation points for mutating ones. I didn’t get t at first, but once I did, I was in love. Perfect for readabiiity.
评论 #17324607 未加载
评论 #17324398 未加载
snappyTertlealmost 7 years ago
Destructuring in almost any functional language and ES6 JS.
amthewizalmost 7 years ago
Ruby&#x27;s optional parenthesis for function calls. Makes beautiful DSLs like RSpec -<p><pre><code> describe UsersController do before do allow(controller).to receive(:current_user).and_return(nil) end describe &quot;GET #new&quot; do subject { get :new } it &quot;returns success&quot; do expect(subject).to be_success end end end</code></pre>
评论 #17324762 未加载
EvenThisAcronymalmost 7 years ago
Hands down, it&#x27;s D&#x27;s shorthand array operations.<p><pre><code> int[] a = [1, 2, 3]; int[] b = a[] * 3; assert(b == [3, 6, 9]); a[] += 2; assert(a == [3, 4, 5]); int[] c = a[] + b[]; assert(c == [6, 10, 14]); </code></pre> This of course works with D&#x27;s slicing syntax so you can do stuff like a[0..1] *= 3.
mabynogyalmost 7 years ago
I use &quot;star&quot; in my programming language to &quot;dereference&quot; generators (run them until they are finished). For example:<p><pre><code> &#x2F;&#x2F;block for 4s sleep* 4 &#x2F;&#x2F;run a modal form let* ok form_confirm &quot;Do you agree?&quot; </code></pre> Those calls are converted to loops.
singularity2001almost 7 years ago
I love kotlin lambdas with «it»:<p>list.filter{ it &gt; 3 }.map{ it + 1 }<p>compare that to shitty Java or C++<p>.<p>Love js map construction by name:<p>fun=&quot;...&quot;; map={fun}; map.fun == &quot;...&quot;<p>Nice lambdas and properties are the things I miss most in python, especially python3, where you have to call list(map(...)) all the time (generators are a good idea but <i>why</i> not add proper __str__?)
jedbergalmost 7 years ago
Python list comprehensions.<p>They could be written as multiline loops, that are definitely more readable, but it&#x27;s just so nice to whip out a list comprehension sometimes:<p><pre><code> print([int((((1 + 5**0.5) &#x2F; 2)**n - ((1 - 5**0.5) &#x2F; 2)**n) &#x2F; 5**0.5) for n in range(1, 21)])</code></pre>
farleykralmost 7 years ago
I just discovered being able to use Python to convert a number to a different base:<p>&gt;&gt;&gt; int(‘x’, y)<p>...where x is the string&#x2F;number you want to convert and y is the base.<p>I haven’t found a practical use case but it’s been a lot of fun to play with.
评论 #17324649 未加载
domlebo70almost 7 years ago
Do notation in Haskell, Scala etc. Nothing else comes close
评论 #17324439 未加载
timwisalmost 7 years ago
JavaScript&#x27;s async&#x2F;await is our reward for suffering promises. Not perfect, but makes the language a lot more approachable IMO.
AndrewDuckeralmost 7 years ago
The one that&#x27;s saved me the most time is probably &quot;foreach&quot; as a way of accessing enumerables in c#.<p>Simple, readable, and easy.
nemoniacalmost 7 years ago
If you use pretty much any lisp-like language you can add your own favourite syntactic sugar to the language yourself.
charlieflowersalmost 7 years ago
possibly async&#x2F;await
RhysUalmost 7 years ago
Haskell dollar operator ($). Last I checked, it fits into the Python grammar if anyone feels PEPpy.
tu7001almost 7 years ago
List comprehension - Python, Haskell.
emorning2almost 7 years ago
async&#x2F;await<p>I see async&#x2F;await as the only way to write asynchronous code that&#x27;s readable
geoelkhalmost 7 years ago
A lot of things in Ruby like<p>if !disabled &#x2F;&#x2F;instead of unless disable
imhalmost 7 years ago
Python 3&#x27;s string formatting is pretty useful.
aqme28almost 7 years ago
Ruby&#x27;s ||=<p>`a ||= b` sets a to b, unless a is already defined.
pdgonzalez872almost 7 years ago
The pipe operator in Elixir.
BigToachalmost 7 years ago
Decorators in any language.
aphextronalmost 7 years ago
range() in Python<p>[foo, bar, ...baz] ES6 Destructuring