24 ms·
Microfeatures I'd like to see in more languages
- armchairhacker 4y agoStrongly-typed units and unit literals (e.g. 3mL, 10gal, 15m / 3s = 5m/s) AFAIK F# has these and that's about it
- ignormies 4y agoI see this in some Rust crates, as you can implement traits for built-in, primitive types. For instance, the `embedded_time` crate lets you do 200.microseconds() 5.Hz() https://docs.rs/embedded-time/latest/embedded_time/ https://docs.rs/embedded-time/latest/embedded_time/
- int_19h 4y agoThey can be implemented as a library C++ thanks to templates and user-defined literals, and there's a proposal to add them to stdlib based on one of the existing implementations: https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p1935r2.html https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p19...
- kwhitefoot 4y agoYou can implement it in C# too with zero run time cost.
- int_19h 4y agoI don't see how, except for manually rolling a struct for every new combination of units. The C# generic system is not flexible enough to define things like "m / s / s = (m/s^2)".
- brabel 4y agoThere's a Java compiler extension, Manifold[1], that adds this to Java. [1] https://github.com/manifold-systems/manifold/tree/master/manifold-deps-parent/manifold-ext#unit-expressions https://github.com/manifold-systems/manifold/tree/master/man...
- perrygeo 4y agoFrink (which OP mentions for its datetime syntax) has the concept of units and unit conversions built into the core language - but that's about all it does! I'd love to have this feature in a general-purpose language.
- dima_vm 4y agoYou can make that in Kotlin, e.g.: `3.mph` or `(-45..45).deg` for ranges. with definition like: val Double.mph: Speed get() = Speed.mph(this) data class Speed(val ms: Double) companion object { fun mph(mph: Double) = Speed(mph * 1609.344 / 3600.0) }
- still_grokking 4y agoSomething like: https://www.scala-lang.org/api/current/scala/concurrent/duration/Duration.html https://www.scala-lang.org/api/current/scala/concurrent/dura... https://github.com/Bersier/physical https://github.com/Bersier/physical https://github.com/RussP/scalars https://github.com/RussP/scalars
- turtledragonfly 4y agoWith regard to strings, they give a good example in Lua, but oh boy wait until this person hears about Perl (: There's a whole section in the manual [1] for string quoting operators (qq, qw, qx, ...) In general, I feel like Perl is one of those languages that has a high amount of these "quality of life" syntactic features, and helps make it enjoyable to write, once you get over the learning curve. [1] https://perldoc.perl.org/perlop#Quote-Like-Operators https://perldoc.perl.org/perlop#Quote-Like-Operators
- mncharity 4y agoRaku (once Perl6) generalizes quoting as a Q , followed by optional "how should this behave" adverbs, and text bracketed by anyish unicode bracket pair. So Q:w <foo bar> is a list of two words. And has Perl-like qw/foo bar/ as sugar. Heredocs are Q:to/THEEND/ ... \nTHEEND . I'm unclear on whether you extend this without defining your own Q-like thing? Julia allows[2] defining your own non-standard string literals. foo"bar"hee and qux`...` desugar as macro calls foo_str("bar","hee") and bar_cmd("..."). But lack the bracket flexibility. http://rigaux.org/language-study/syntax-across-languages.html#Strng http://rigaux.org/language-study/syntax-across-languages.htm... briefly sketches other languages. [1] https://docs.raku.org/language/quoting https://docs.raku.org/language/quoting [2] https://docs.julialang.org/en/v1/manual/metaprogramming/#meta-non-standard-string-literals https://docs.julialang.org/en/v1/manual/metaprogramming/#met...
- dariusj18 4y agoThat's actually a great point. Perl has so many syntactic sugars that it is a poster child for too much variety in ways you can write things. Making it much harder to read someone else's code.
- masklinn 4y agoPerl has so much syntactic sugar it's the poster child for syntactic diabetes, really.
- jodrellblank 4y ago
- happyrock 4y agoI have long wondered why Ruby's symbols aren't in every language.
- revskill 4y agoIs it for performant reason ?
- onei 4y agoSymbols in Ruby are meant to be more performant that strings iirc. If I have symbol :a, then it's allocated once regardless of how many time it appears. As opposed to "a" which is reallocated every time. I guess it's similar to Python having a single instance of small integers. PlayStation also experimented with caching small floats which gave them some perf improvements too, but I think wasn't as performant in all cases.
- justincormack 4y agoLua (and some other languages) intern strings, so all strings that are the same point to the same string instance. This gives the same benefits (plus string equality is just pointer equality) without a different type.
- pawelduda 4y agoThere is a caveat in older Ruby versions that they aren't garbage collected, so they shouldn't be used for things like user input. Not a problem since 2.2 though.
- progval 4y agoSymbols can even improve performance. Replace them with integers at compile time like a global enum, and so the runtime only needs to compare integers instead of potentially lengthy (especially if UTF-16) strings.
- masklinn 4y ago> Replace them with integers at compile time like a global enum, and so the runtime only needs to compare integers instead of potentially lengthy (especially if UTF-16) strings. All of those strings will be interned, and can thus be compared by identity. Which is an integer comparison.
- orangepanda 4y agoPhp supports kebab-case variables: ${"variable-name"}=123; Isnt it beautiful?
- oconnor663 4y agoHow many languages support kebab case with any Unicode dash that isn't the ASCII one? :)
- adastra22 4y agoProbably any language that supports Unicode identifiers.
- jfoutz 4y agoAt the moment, the only one I know for sure is Agda. I suspect java would work as well, not sure about golang unicode var naming.
- zimpenfish 4y agoplay.golang wouldn't let me use figure (‒, U+2012), endash (–, U+2013) or emdash (—, U+2014) in a variable name directly. But then the spec[1] says that only code points characterised as "Letter", an underscore, or characterised as "Number, decimal digit" are valid. [1] https://go.dev/ref/spec#Identifiers https://go.dev/ref/spec#Identifiers
- leipert 4y agoCoptic Small Letter Dialect-P Ni should work, looks like a hyphen. Go Playground: https://go.dev/play/p/kxgOcEWsznz https://go.dev/play/p/kxgOcEWsznz https://www.compart.com/en/unicode/U+2CBB https://www.compart.com/en/unicode/U+2CBB
- zimpenfish 4y agoOh, neat catch!
- xigoi 4y agoMy favorite is uniform function call syntax. In several languages (Nim, Koka, D, …), you can always write bar.foo(baz) instead of foo(bar, baz) and vice-versa. Another one from Nim is the implicit result variable. Instead of having to do this: func sum(nums: seq[int]): int = var result = 0 for num in nums: result += num return result you just do this: func sum(nums: seq[int]): int = for num in nums: result += num It saves so much time and I'm disappointed that more languages don't have it.
- onei 4y agoI think you can also do the second in Go with named returns, e.g. func sum(nums []int) (result int) { for _, n := range nums { result += n } } No clue if it's an idiomatic usage, and named returns always felt a little too magic for me.
- zimpenfish 4y agoIt's kinda fine if it's a short function like that[1]. When you get above 10-15 lines in a function though, it's easy to lose track of what's a return variable and what isn't. [1] and everything in the codebase uses that style otherwise it's annoying to have to context-switch every 5 minutes.
- mikepurvis 4y agoLots of languages will implicitly return the final expression— I feel like that's a decent compromise. Not quite as magical as an actual named variable that just exists, but not as clunky as needing as explicit `return` every time.
- tsimionescu 4y agoHonestly, I don't like that style for languages which allow multiple side-effects as well. For example, (progn (print "something") 0) Is honestly pretty ugly from my point of view.
- prpl 4y agoI wrote a small DSL for easy compilation to SQL that included some similar features. It included datetime literals, but they were specified as just a string prefixed with "d". d'2020-02-20' I also tried to make it so that every comparison had both english and symbol representations, a range syntax, and an approximation/match comparison (e.g. "=~", "!~") which could work with both floating point numbers and strings properly. I found this useful, and wish it was in more languages.
- still_grokking 4y agoComparing floats is not a great idea, though. That's a foot gun.
- pishpash 4y agoGreat, introduce slang to languages, what could go wrong?
- jedisct1 4y agoSlang itself is a language: https://www.jedsoft.org/slang/ https://www.jedsoft.org/slang/
- pgorczak 4y agoClojure’s loop expression hits this spot for me. It sets a recursion point to which you can jump using any logic inside the body you want, as long as it is from tail position. It’s like a while loop turned into an expression. I haven’t encountered any other way to write iterative expressions whose number of iterations isn’t known at the top (like map and reduce).
- japanman425 4y agofor x in y: yield x Job done
- wging 4y agoTail call optimization can get you that, too. If you've written Scheme and/or gone through SICP you might be familiar with this: you write a recursive function, with the recursive function call as the last thing the function does ('tail-recursion'), and the compiler/runtime is able to optimize those recursive calls out rather than consuming one stack frame of space per call ('tail call optimization'). Clojure has loop/recur at least partially because it doesn't support tail-call optimization. See https://en.wikipedia.org/wiki/Tail_call https://en.wikipedia.org/wiki/Tail_call for more. Or SICP might be a good resource. https://sarabander.github.io/sicp/html/1_002e2.xhtml https://sarabander.github.io/sicp/html/1_002e2.xhtml
- amalgamated_inc 4y agoInterestingly, I almost prefer Clojure's `recur` semantically. Means you don't have to change the function name twice if you rename it, and it's hard to miss that you're recursing.
- 4ad 4y ago> Instead of writing 10000500, you can write 10_000_500, or 1_00_00_500 if you’re Indian. I hate this so much. It means I can't grep for a constant.
- overengineer 4y ago1_?0_?00_?0_?500 yes it sucks
- elygre 4y agoThat’s not enough — the underscores can appear anywhere, so you need to cater for 500000_0 and 5_0_0_0_0 etc. basically an optional underscore between each digit.
- amalgamated_inc 4y agojust grep for `[0-9_]+`
- masklinn 4y agoI would assume they're looking for a specific constant value.
- gpderetta 4y agogrep '[0-9_]+'|sed 's/_//g'|grep <my-constant>
- amalgamated_inc 4y agoThat's kind of a handful to type every time :) I'd just do for the first one and then scan for the number I'm interested in. If you have more than a page full of constants..
- nicoburns 4y ago
- mr_mitm 4y agoI really liked the postfix and prefix notation in Mathematica. These three all mean the same: f[x] f@x x // f It matches the flow of thought more naturally when hammering out a couple of one-liners.
- japanman425 4y agoHow is that third one readable at all? I’d assume it meant integer division.
- deleted 4y ago[deleted]
- mr_mitm 4y agoThat's just a matter of habit. The exact symbol isn't important anyway.
- Smaug123 4y agoMathematica uses a lot of syntactic sugar. You will find all Mathematica code unreadable until you've learned to read it; `//` is no exception.
- contravariant 4y agoI find Mathematica code unreadable full stop. Its convenient when writing though.
- mr_mitm 4y agoI see Mathematica as a shell for math. You can write long programs or modules in it, sure, but very often you're simply typing up a couple of lines to check some computation or visualize an expression which you won't even save, in which case readability is secondary.
- carry_bit 4y agoIt's usually used with the formatting functions, so you have something like: <Some big expression here> // Column Useful where the function in question is an "afterthought".
- masklinn 4y ago> If you look at something like numpy functions, so many of them share the exact same parameter definitions. What if you could write def log(standard-exp-params) instead of having to write them out every single time? They're not actually written out every time, the issue is mostly documentary (and it would be nice if Python or Sphinx ever had a good solution). And numpy actually has a bunch of generators for that e.g. https://github.com/numpy/numpy/blob/45bc13e6d922690eea43b9d807d476e0f243f836/numpy/core/code_generators/ufunc_docstrings.py https://github.com/numpy/numpy/blob/45bc13e6d922690eea43b9d8... handles filling in the common bits of documentation for the ufuncs.
- PyWoody 4y agoI don't use Numpy but it sounds like they're describing *, ** operators. default_args = ('x', 'y', 'z') default_kwargs = {'p': 'p', 'q': 'q', 'r': 'r'} def printer(x, y, z, /, *, p, q, r): print(f'x={x} | y={y} | z={z} | p={p} | q={q} | r={r}') printer(*default_args, **default_kwargs) # x=x | y=y | z=z | p=p | q=q | r=r EDIT: Formatting.
- masklinn 4y agoYes but also that lacks most of the documentation so it's not great. If you have multiple callables taking these parameters documenting them is awkward, by default help/pydoc and sphinx will tell you that the parameters are `default_args` and `default_kwargs`, but that's not actually true, those are just intended as shortcuts / helpers .
- davidhyde 4y ago> You can write # 2001-08-12 # to mean the date 2001-08-12, instead of writing something annoying like Date(2001, 8, 12) I like this article but oh man dates just trigger me. Such a missed opportunity to use an unambiguous date example like 2001-08-13
- jakeinspace 4y agoYear-day-month would be a truly cursed assumption for a format
- iwsk 4y agoIt would have been unambiguous in a world where we all agreed that both months and days start at 0 :)
- unnouinceput 4y agoAlso don't forget about year 0 (which doesn't exists and is a single point of failure for so many programs that deal with calculating time between now and a BC date)
- zokier 4y agoIf only anything with calendars was that clear-cut. ISO 8601 does have year zero.
- lelanthran 4y ago> It would have been unambiguous in a world where we all agreed that both months and days start at 0 :) How so? Would 2021-08-12 mean month 08 or month 12? It doesn't matter if it starts from zero, it still looks ambiguous to me.
- still_grokking 4y agoYeah, sure, because normal people count form zero… Have you actually ever watched people counting things? In a sane world the offset based counting (zero bases) would have never surface (besides in very specific and seldom circumstances). Also it's a shame that the C languages started to call offset "index" (and there is not even a proper index operator!).
- surfsvammel 4y agoI love all the sugar of Kotlin, but there is one thing I miss, and it is the indexing of arrays of Python when pulling out part of an array.
- amalgamated_inc 4y agoKotlin is so close on so many things, but then keeps messing up. arrayOf(1, 2, 3) - why not [1,2,3]? emptyArray() - why not []? mapOf("key" to "value") - why not {key => value}? These are all solved problems. Why would they make up some harshly suboptimal syntax?
- kaba0 4y agoI am not that familiar with Kotlin, but these seems better than the syntax primitives from a language design perspective (I greatly recommend the “Growing a language” presentation done by Guy Steele), these are ordinary functions that are well-known from other parts of the language, not an added “hack” that has a one-off use. If you were to use a concurrent hashmap implementation you no no longer can use the syntactic sugar, and writing against an implementation is quite common in Java (which plays quite a big role in the design of Kotlin), e.g. having a List in the interface, instead of ArrayList.
- amalgamated_inc 4y agoInteresting, I think the exact opposite :)
- dima_vm 4y ago`{key => value}` it should be mutableMapOf() just as well. Same for array.
- switch007 4y agoComing to Kotlin from Python, these always get on my nerves. My brain hasn't adjusted to needing to call a function. And 'X to Y' just doesn't click for me. I guess I'll get used to it eventually
- jedisct1 4y agoComptime. After having discovered Zig, I've been missing that feature in every other language.
- amalgamated_inc 4y agoCompare to lisp macros?
- AnIdiotOnTheNet 4y agoAnd error unions with corresponding semantics. And explicit casting requirements. And @TypeInfo. And no hidden allocations. And probably like 4 or 5 other things I'm not thinking of right now.
- Deukhoofd 4y agoComptime is great, but I wouldn't classify it as a microfeature. It'd fall more in the second category the author defines.
- deleted 4y ago[deleted]
- gavinhoward 4y agoFor me, yes and no. Sure, comptime is great, but I've also found it hard to reason about code with it. I prefer my comptime stuff separated out into its own section/file/whatever. With that small change, it becomes so much easier. But yeah, still powerful and nice.
- still_grokking 4y agoZig would be great if it took security more serous. As long as you're ending up with the same problems as in C/C++ it can be as great as it likes it will stay a language of the past.
- light_hue_1 4y agoHaskell has almost all of these. > Instead of writing 10000500, you can write 10_000_500, or 1_00_00_500 https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/numeric_underscores.html https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/nume... > Balanced string literals https://hackage.haskell.org/package/raw-strings-qq-1.1/docs/Text-RawString-QQ.html https://hackage.haskell.org/package/raw-strings-qq-1.1/docs/... > Generalized update syntax Use Lens. `fileName %~ max 2` > you can write the sequence 1, 2, … n-1 as 1..<n. Yup. `[1,2..n-1]` There's far more to it, you have access almost a SQL-like sublanguage. > Symbols In Haskell you use hash has a prefix instead of colon. Haskell sadly does not do automatic lifting, no extended parameter blocks, and no kebab-case.
- unhammer 4y ago>> Symbols > In Haskell you use hash has a prefix instead of colon. Can you give an example?
- light_hue_1 4y agohttps://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/overloaded_labels.html https://ghc.gitlab.haskell.org/ghc/doc/users_guide/exts/over... You can do all sorts of things with them. Use them like symbols in Scheme, say to name fields `get #name user` or to access database tables, etc. But what's even more interesting is that the name is reflected up into the type. `get #name user` won't fail at runtime. Your database table name can be checked at compile time.
- unhammer 4y agoAh, OverloadedLabels – I've only seen them in the `get #name user` use-case. I feel like Scheme/Lisp symbols are used quite a bit more generally, but maybe it's just not caught on yet in Haskell, also other features fill the same roles (e.g. in many lisps you can unquote a symbol and use it as the function of that name; people also often use them similarly to data constructors for pattern matching).
- still_grokking 4y ago
- Doctor_Fegg 4y agoNegative array subscripts. So a[-1] means the last element of an array, a[-2] means the second last, and so on.
- scubbo 4y agoI was really surprised when I learned my second language (after Python) to realize that this wasn't standard!
- unnouinceput 4y agoThat's for languages that can't define arrays with custom start/stop indexes. But those that have custom indexes they can very easily expand/implement as helper class (for example array.indexFromLast(1) which means array[Length(array)]. This way you can have best of both worlds.
- masklinn 4y agoSurely if your language has custom indexes / ranges `Length(array)` is completely broken and the language provides something like "Index`Last" you can hook on? Because an array with indexes [3, 7) has length 4, but 4 is not the index of the last element.
- kqr 4y agoYes, then I would expect 'First and 'Last with the obvious meaning, and something like 'Range which returns an iterator of all indices.
- unnouinceput 4y agoYup, correct. What I meant above with array[Length(array)] is for the languages that don't have it. Let me be more clear. C/C++ doesn't have custom array indexes and as such <array[std::size(array) - 1]> is returning the last element of said array. Delphi has custom array indexes and as such, taking your example with defining an array in the form <example_array : array[3..7] of integer>, I would not get the last element in case of <example_array[Length(example_array) - 1]. In this case I would have 2 options. Option 1 would be to use <High> function as in <example_array[High(example_array)]> to access example_array[7] element. Delphi also has <Low> function so you can iterate through a custom defined array by using <for> keyword with the help of them. Option 2 would be to actually build my own helper (this is the most wanted case when you're dealing with multi-dimensional arrays that also have custom indexes) and I would have something like <example_array.FromLastIndex(0)> to access example_array[7] element. Hope this cleared the confusion.
- amalgamated_inc 4y agoElixir's sigils are amazing. There are date sigils that allow you to do what the OP does: ~N[2023-01-01 12:00:00] But you can also define your own sigils to create new "custom syntax" for almost any struct. Kind of a special case of reader macros, I guess. Very convenient.
- cschmatzler 4y agoThe most recent addition to the digit family being Phoenix’s new ~p”/healht”, which is a HTTP route string that automatically verifies whether the route exists, and returns compile-time warnings when you link to a path that didn’ doesn’t. It’s fantastic, and really surprising it took this long to be added to any web framework.
- mncharity 4y agoElixir sigils[1][2]. Eg: ~w(foo bar bat) is a word list. `~ letter bracketed-text lettersasmodifiers` desugars as sigil_<letter>(text,modifiers). Similar to foo_str() of Julia[3], but for one-letter-names and more brackets. But not the unicode brackets of Raku. [1] https://elixir-lang.org/getting-started/sigils.html https://elixir-lang.org/getting-started/sigils.html [2] https://hexdocs.pm/elixir/main/syntax-reference.html#sigils https://hexdocs.pm/elixir/main/syntax-reference.html#sigils [3] https://docs.julialang.org/en/v1/manual/metaprogramming/#meta-non-standard-string-literals https://docs.julialang.org/en/v1/manual/metaprogramming/#met...
- Aaargh20318 4y agoSwift has the expressiblebyTypeliteral series of protocols for this. For example you could write an extension on Date to add initialization from a string: extension Date: ExpressibleByStringLiteral { public init(stringLiteral value: String) { // parse the string here. } } You can then do things like: let happyNewYear: Date = “2023-01-01 12:00:00” There are a protocols for all literal types. For example, you could implement ExpressibleByIntegerLiteral and have have it init the Date object from a unix timestamp. There is even an ExpressibleByNilLiteral.
- 4y ago
- jb1991 4y agoI would add named function parameters to this list. So useful.
- ufo 4y agoLua also allows you to choose the string delimiter. If your string contains "]]" you can delimit it with [=[ or [==[ instead. Any number of "=" so long as the opening and closing delimiters match.
- unnouinceput 4y agoAnd that's why all modern languages implement streams/string helpers/string builders. You do not want to actually write strings/manipulate them using "+" (concatenation symbol) in code directly because, in modern Unicode world, it tends to become a point of failure for obscure bugs / a maintenance horror show.
- jbverschoor 4y agoI don't understand the link with parent, nor why + would be bad, besides a) because language is naive about concatenation / allocation, and b) if the language allows / doesn't differentiate between a char 'x' and an integer, bc that would result in an integer addition instead of a concatenation.
- unnouinceput 4y agoIf you manipulate strings in code using "+" (string concatenation symbol) from a user input you'd be in a world of hurt where you either do a lot of regex (which is ugly and unmaintainable) or you limit the user input to known characters only (which would be a bad user experience and later on your manager would ask you to lift such constraint anyway because they want to support a new feature from now on). Therefore you use, for example, a stream and simply dump your user input in the stream buffer, as they come, and go with that stream in your code from that point on. This way you're future proof too if your manager wants a new feature to support, as example, Chinese and/or Japanese keyboard
- lolinder 4y agoNot OP, but I'm still confused. Is this assuming that the language is naive in its implementation of string concatenation so it screws up Unicode? I'm just not sure what the syntax has to do with the semantics of string concatenation.
- keybored 4y agoAgree with kebab-case. > Most languages have multiline literals, but what makes the Lua version great is that the beginning and ending marks are different characters. This solves the infuriating “unnestable quotes” problem string literals have, and you don’t have to escape all your literal \s. That paragraph also uses “nestable marks”.
- jonasenordin 4y agoNestable comment syntax is also nice. At least some MLs (eg SML) has it, that I know of. Indentation-sensitivity can also solve similar problems. (Indentation does not have to exclude requiring graphic termination. A formal language can require both. Or just a helpful tool.) (Also agree with 'kebab-case', although the name is new to me and a bit weird.)
- lolinder 4y agoWhat makes C-style comments unnestable?
- gpderetta 4y ago/**/ could potentially be nestable, they are just not defined as such.
- funcDropShadow 4y agoThey are defined to be non-nestable. Any appearance of */ terminates the comment.
- still_grokking 4y ago> Nestable comment syntax is also nice. At least some MLs (eg SML) has it, that I know of. Scala has it too. (But OK, Scala is a kind of ML).
- nwellnhof 4y agoFWIW, Raku and XPath support kebap-case. If you really mean subtraction, you have to add whitespace.
- duped 4y ago> Second, what if parameter blocks were abstractable? Sounds like a great way to make unreadable code #define STANDARD_EXP_PARAMS ... // I hit gotodef on func(...) and got here. What are the arguments? void func (STANDARD_EXP_PARAMS) { // ... long function body ... x = y; // What is the type of x? Is it an argument or a local? } I'd really be irritated if someone ever used this feature, optimizing for lines written is shaky territory to begin with. When it's at an interface boundary it's not excusable. NB4 "use an IDE" - requiring an IDE to make code legible is dumb, and I'm an IDE shill!
- robertlagrant 4y agoYou could say the same about a function call or a function that takes an object as an argument - who knows what code lies behind the impenetrable barrier of structured or object oriented programming?
- duped 4y agoThat's actually a feature of encapsulation. The object (ideally) is used to abstract away those details so I don't need to know about them, only how to create the object. Encapsulation is a different feature than reuse. The exception is in languages that use that syntax as a way to implement keyword arguments, but I would still ask people to destructure it in the parameter list or at the top of the function so I can see what the arguments are. The point is that when I am looking at a function definition I need to know how to call it. As described all I see is obfuscation to save some keystrokes, not clean code.
- robertlagrant 4y agoBut how would you know how to call it if it takes an object as an argument? How different would the process be for looking at a named standard set of arguments?
- duped 4y agoPython's `with` Function composition operators eg a |> b # Call `b` with `a` as an argument b <| a # Same as above, reversed direction Then you can do something like let x : Map = collect <| [a, b, c] |> map(entries) |> flatten
- whatshisface 4y agoI don't get it, how are |> and <| any different from parentheses?
- mikepurvis 4y agoChaining without nesting.
- whatshisface 4y agoIf you mean without closing parentheses, I think you can also do that in languages like Haskell with non-parenthetical function calls.
- mikepurvis 4y agoI'm not a Haskell user, but my experience with this in the Nix language is a bit mixed. It definitely works sometimes, but then you get a pileup of parenthesis nesting anyway, because the default is greedy and you have to control which functions get which arguments.
- nine_k 4y agoDon't $ signs work in Nix the way the work in Haskell? E.g. https://mmhaskell.com/blog/2021/7/5/function-application-using-the-dollar-sign- https://mmhaskell.com/blog/2021/7/5/function-application-usi...
- mikepurvis 4y ago
- andix 4y agoI want more implicit typing in typed languages. Quite often the compiler knows exactly what type a function will return, but I still need to write it there. Sometimes it’s easy („int“), but what about HashSet<Immutable<Tuple<int,string>>> Typescript does it well. F# (completely statically typed) too…
- mikepurvis 4y agoRust does a pretty decent job of this, particularly around functions that return collect(). But yeah, C++ has a ways to go on type inference.
- tlb 4y agoBetween `auto` and `decltype(auto)` it mostly does what I want, although the 2nd syntax is frightful. The main case it doesn't handle is for (auto i = 0; i < foo.size(); i++) where obviously I want i to match the return type of foo.size(), so a size_t rather than an int.
- kaba0 4y agoNowadays even Java will do that, var list = yourFunctionReturningThatSet();
- andix 4y agoAlso on a function? var getDate() { return „no date“; }
- nicoburns 4y agoOne of the best truly micro features I've seen recently (can't remember which langauge unfortunately - it wasn't a mainstream one), is general binary literal syntax of the form: 0x[de ad be ef 00] So much nicer than the usual condensed format. And I think it'd be valid syntax in any language that allows binary integer literal.
- andix 4y agoA lot of languages allow underscores in numeric literals. Something like 10_000. You can put them anywhere and they get ignored. I don’t know if they also allow it for hex numbers.
- masklinn 4y ago> I don’t know if they also allow it for hex numbers. They do e.g. Python >>> 0x_ab_cd_01_23 2882339107 or >>> 0b_0010_0100 36
- rwmj 4y agoEven C these days, although they chose ' instead of _ :-(
- kwhitefoot 4y agoMy guess is that they did that because there are real human languages where ' is used as a thousands separator.
- xigoi 4y agoThere are also real human languages where a space is used as a thousands separator, and an underscore is kind of the programming equivalent of a space.
- kwhitefoot 4y ago
- andix 4y agolocal const variables like JavaScript has them. You can declare variables with „let“ (mutable) or „const“ (immutable). This is really great when reading code, because you never have to check if some code may change the variable at some point. And you usually declare most variables as const. A lot of languages provide immutable variables only for class members or statics, but not for local variables.
- kaba0 4y agoI really like Scala’s `val` vs `var`.
- andix 4y agoOkay, that would confuse me. Looks very similar and easy to overlook.
- jlokier 4y agoSyntax highlighting can help with distinctions like that. You might prefer Nim's visually distinct "let" for immutable, "var" for mutable. "const" is also available and means resolved to constant at compile time, similar to Zig's "comptime".
- culi 4y agoit hurts that `let`, `var`, and `const` are all used in JS and mean completely different things. `let` even means the exact opposite
- still_grokking 4y agoActually not, as firstly you almost never use `var`s, and secondly if you do, most syntax highlighting rules will make them shine in bright color as something very exceptional.
- sureglymop 4y agoSame in Kotlin
- mncharity 4y ago> roughly three classes of language features [...] 3. Quality-of-life features that aren’t too hard to add I'd regrettably add another class, quality-of-life features which you'd have hoped weren't too hard to add, but because of past choices, now are. Examples: Adding javascript-like dots a.b.c for Julia Dict's a[:b][:c] would conflict with "wasn't intended to be public but has been" Dict implementation fields, like .count . Adding { a,b | ... } instead of a less concise { |a,b| ...} for Ruby blocks, but for a yacc grammar conflict.
- lamontcg 4y agoYou can build method access in Ruby trivially enough but you will forever be explaining to users which node.class isn't node[:class]. And now every method added to that Hash/Dict-like object is a breaking change because someone somewhere could have used that already to access a key. The { a,b | } syntax is also still ambiguous with hash literals, unless you require that | to be there, and that looks like it gives the parser a whole lot of look-ahead work to do in order to distinguish hashes from lambdas.
- seanalltogether 4y agoI really like swift's simple way of collapsing try catch blocks down to a simple value|nil result. let data = try? aFuncThatThrows() Sometimes I just don't care about the reason for the exception and just want to know if it succeeded or not
- armchairhacker 4y agoRust does this too with `Result::ok`
- deleted 4y ago[deleted]
- btown 4y ago> [In Chapel] there’s the config keyword. If you write config var n=1, the compiler will automatically add a --n flag to the binary. As someone who 1) loves having configurable program, and 2) hates wrangling CLI libraries, a quick-and-dirty way to add single-variable flags seems like an obvious win. Letting people define configurable variables at their call site is incredibly valuable, even if you don't have compile-time support, and even if you're working on something not meant to be an isolated binary. At my startup, one our most beloved innovations is that you can write `resolve_config("foo", default="bar", request=request)` pretty much anywhere you'd normally hardcode a value or feature flag... and that's it. The first time it's seen in any environment, it thread-safely inserts-if-not-present the default value into a key-value storage that's periodically replicated into in-memory dictionaries that live on each of our app servers. Any subsequent time it's accessed, it's a synchronous key-value lookup in memory, with barely any overhead. But we can also configure it in a UI without needing a code redeploy, and have feature flags and overrides set on a per-user or per-tenant basis. Sometimes, you don't need language support if you have some clever distributed-systems thinking :)
- masklinn 4y ago> The first time it's seen in any environment, it thread-safely inserts-if-not-present the default value into a key-value storage That seems like a great way to get amazingly hard to replicate bugs or odd behaviours if different subsystems use different values for the default.
- elcritch 4y agoYou'd just need to have a mutex lock on the values. That could be slow, but you probably don't want to have a config flag in a hot loop anyways. :) In Nim you can do compile flags which let you set constants so you avoid the problem: const myLibraryVersion {.intdefine.} = 3
- masklinn 4y ago> You'd just need to have a mutex lock on the values. Oh no they're saying that it's thread-safe, that's not an issue. Rather that depending on the order of initialisation, possibly of different systems entirely, you can have different initial states because different systems or subsystem decided of the default value.
- rwmj 4y agoPerl's if and unless operators, which can also be postfixed, eg: die "can't be negative" unless $i >= 0; Perl is full of usability features, like <> for reading input, inline literate coding annotations, implicit $_.
- lullab 4y agoI'd like to see the "in" operator from SQL in C-style languages. Something like: if(x in (null, 2, 3.14, foo(123)) { // }
- still_grokking 4y agoCollection.contains()? That's a pretty std. feature I guess.
- devmunchies 4y ago# Function Shorthand #### I like how functions in js can be `arg => result`. In F# I have to do `fun arg -> result` with the `fun` keyword. It makes sense since `MyArgType -> MyResType` is a type signature in f#, but I feel like the compiler can just check if the arguments are references to types or are argument bindings. # Multiline Lists/Arrays #### I like how F# doesn't require delimiters for multiline lists. So I can do `let myList = [1; 2; 3]` or let myList = [ 1 2 3 ] # Regex Literal #### I like how in Crystal instead of doing `/my[regex]/` i can do `%r(my[regex])` where the parenthesis can be any brace type (like "(", "{", "<", "[") so I don't have to escape any characters. # Argument Accessor Shorthand #### In Crystal, you can use an ampersand to bind and access a property on an object, instead of writing the verbose form with a function. So this ["a", "b"].join(",") { |s| s.upcase } can be written as ["a", "b"].join(",", &.upcase) If this were available in F#, for example, instead of ["a"; "b"] |> List.map (fun s -> s.ToUpper()) |> String.concat "," I could do ["a"; "b"] |> List.map &.ToUpper() |> String.concat ","
- dan-robertson 4y agoThe function syntax I like even more is one with implicit arguments so you don’t have to name them, e.g. waiting = sum workers #(%.in_queue + %.in_flight) Clojure has some syntax like this though it isn’t needed for the most obvious use-case of functions to extract fields because keywords, which are usually used for map keys, are implicitly functions that look themselves up in their arg, e.g. (:bar { :foo 3, :bar 2 }) ; => 2
- masklinn 4y ago> I feel like the compiler can just check if the arguments are references to types or are argument bindings. 1. this is absolutely terrible because now you need feedback from the type checker to know how to parse the program 2. it is furthermore also ambiguous with function application, requiring arbitrary lookahead to disambiguate, also not a fun thing to do JS gets away with it because the sigil was not previously used and it only requires a single lookahead to parse, as only single-parameter anonymous functions can have "bare" parameter lists.
- tobyhinloopen 4y agoElixir’s testing library uses meta programming to show the code that fails and what the values were at both sides of a comparison. IE a = 1; b = 2 assert a == b Will fail with error like: Assertion failed, a == b Left is 1 Right is 2 So you don’t have a bunch of assert-functions; you just assert anything and it will spit out a decent error.
- elcritch 4y agoYes! That feature is great. I got used to it in Elixir and Nim provides it as well. It's one of those little things that makes programming nicer.
- masklinn 4y agoWith how old pytest is, I assume that's where they got it from. Does it perform recursive value printing, or bespoke comparisons? e.g. in pytest it won't just print out the values of "a" and "b", it will recursively document intermediate values until it's reached the toplevel expression: assert f() == g() assert 42 == 43 where 42 = <function TestFailing.test_simple.<locals>.f at 0xdeadbeef0002>() and 43 = <function TestFailing.test_simple.<locals>.g at 0xdeadbeef0003>() and it's possible to customise the report so you can report as a diff: assert "foo 1 bar" == "foo 2 bar" - foo 2 bar ? ^ + foo 1 bar ? ^
- cpurdy 4y agoThis is one that I like a lot. Years ago (1997 timeframe) I had implemented it in a Java compiler, and a few years later in a Java library (https://github.com/oracle/coherence/blob/4e6e343e1ffd9bbfea3fb48f2e53f2a990be5731/prj/coherence-core/src/main/java/com/oracle/coherence/common/base/StackTrace.java#L337 https://github.com/oracle/coherence/blob/4e6e343e1ffd9bbfea3...) that would create an exception on the assertion failure and parse its stack trace to find the source code file name, and read it to find the text of the assertion that failed, etc. so it could build the error message ... In Ecstasy, we built the support directly into the compiler again: val a = 1; val b = 2; assert a == b; Produces: IllegalState: a == b, a=1, b=2
- still_grokking 4y ago
- perlgeek 4y agoSome from Raku (formerly Perl 6) that I really like: * sub MAIN: sub MAIN(Int $x, :$verbose) { } generates a command line parser that expects an Integer plus an optional named switch --verbose * It has named params (as seen above), and there are abbreviations: instead of thing => $thing you can write :$thing to avoid duplicating the name (:thing also exists, though it create a pair "thing" => True, so ruby lovers need to be careful :D ) * junctions for quick conditionals/validation: 0 <= all($x, $y, $z) <= 2 * pi * this is a probably debatable, but: if you use a * as a term, it will create a lambda for you, so *+2 is similar to sub ($x) { $x + 2 }
- zem 4y agophasers are brilliant too. so much nicer than all the clunky workarounds for "the first/last pass through this loop needs to be treated specially"
- deleted 4y ago[deleted]
- mhd 4y agoWhat I'd like to have brought back is basically the extended version of the numbers/kebap-case: Ignore white space in constants and identifiers if possible, like Algol-68 did. That means you can write your number as "1 000 000" and put it in the variable "one million", and then feed that to your function called "withdraw money". Yes, sure, makes it harder to grep. Here's a nickel, get a better grep tool (or wrapper thereof).
- ljm 4y agoRuby’s symbols are undersold in terms of how useful they are and how they enable meta programming and DSL development. You can basically invent new language keywords with them. private def foo “bar” end In this case, ‘def foo … end’ returns ‘:foo’, and ‘private’ is just another method that takes it as an argument and decorates the provided method. It’s not a special language keyword.
- jamincan 4y agoFor rust, it is probably the try (?) operator. Fundamentally, it's just syntax sugar for a match statement with an early return in the Error or None cases, but it really improves the ergonomics of dealing with Result and Option types.
- mncharity 4y agoHere's Rust's try (?) operator.[1] It seems sugar for handling short-circuiting return values. A bit like Swift's try? which converts throws to nil.[2] Less so javascript's short-circuiting optional chainging `?.`[3], which I thought of first. [1] https://doc.rust-lang.org/std/ops/trait.Try.html https://doc.rust-lang.org/std/ops/trait.Try.html [2] https://docs.swift.org/swift-book/ReferenceManual/Expressions.html https://docs.swift.org/swift-book/ReferenceManual/Expression... then /Try Operator/ - section anchors don't look stable. [3] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
- randomdata 4y agoInterestingly, there was once a solid effort to add a try operator to Go. While the proposal was quite well received, upon closer inspection it was realized it would be essentially useless in the real world as, given how the rest of the language works, you almost never would want to simply early return with the value received. The data revealed that the vast majority of the code in the wild that the syntax sugar would replace returned something else. So while it is indeed a nifty feature if the rest of the language is also designed for it, it's not something that is easily tacked on to a language that is not.
- int_19h 4y agoIn Rust, when you use `?`, it includes a step to convert the error type of the expression it was used on into the (possibly different) error type that the current function returns. So if you need to map low-level errors to high-level ones in a consistent way, you'd just do it once when defining that error type.
- AnthonBerg 4y agokebab-case enkebab–case emkebab—case These use dash, en dash and em dash, respectively. Most languages that allow you to use a decent amount of Unicode in variable names probably will accept that kind of kebab–case. Those dashes look pretty similar to each other in monospaced fonts but not indistinguishable, so it’s readable and not super confusing. Might work. Why not?
- purplie 4y agoDeclaration of units for primitive numeric variables. Example: <https://github.com/mchrisman/variables-with-units-language-proposal https://github.com/mchrisman/variables-with-units-language-p...>
- mncharity 4y agoJulia's Unitful[1] is actively pushing on physical units. [1] https://github.com/PainterQubits/Unitful.jl https://github.com/PainterQubits/Unitful.jl
- still_grokking 4y agohttps://news.ycombinator.com/item?id=34303858 https://news.ycombinator.com/item?id=34303858
- krapp 4y agoOmitting parens in a function signature when calling with one or no arguments.
- dragonwriter 4y agoThis means you can’t reference the function itself by name without some kind of quoting construct or other circumlocution; also, while the no-arg case might make sense as a special case, if you allow the one arg case, you might as well admit the general case.
- krapp 4y agoThe single argument case works fine for Lua but maybe the no argument case woudn't. Having to supply only the empty argument list seems counterintuitive, though. Variable sigils would work but that would be even more annoying.
- jlokier 4y agoThe general case adds ambiguity which makes it more of a design choice, rather than an obviously good generalisation. In the general case of 2 or more comma-separated arguments, is "func a, b" a call with two arguments, or a tuple containing a call with one argument? Feel the same about "x = (func a, b)"? What about when this appears in list syntax like "[x, y, func a, b]", or the argument list of another function like "obj.method(x, y, func a, b)"? They are easily solvable with a design decision about precedence, but arguably the syntax is a little confusing or worth a warning in all but simple cases.
- sanderjd 4y agoThis is my least favorite example of this kind of thing. This creates so much unnecessary confusion.
- dima_vm 4y agoKotlin has it, but only if the function accepts the function argument, e.g. `foo({println("hello")})` is the same as `foo {println("hello")}` (larger example in my other comment above). You can also make it on no-args function, if it's a method (attached to a type). Utilizing @get(), like that: `3.mph` and have somewhere else defined val Double.mph: Speed get() = Speed.mph(this)
- ivan_gammel 4y agoMore sugar for reflection: class Foo { @Max(10) int bar; @NonNull String name(); } var field = @Foo::bar; var max = @Foo::bar.Max; var method = @Foo::name; var foo = new Foo(); var name = method(foo); var bar = foo.field;
- still_grokking 4y agoJust use a dynamic language like JS if you like code like that.
- atq2119 4y agoI'm partial to for-else-loops. They fit perfectly into languages with compound expression (produce a value from a break in the loop or from the else block). They don't come up that often, but when they do they're really the best solution.
- skykooler 4y agoThey also seem to be unknown to a lot of Python programmers unfortunately; I’ve had PRs rejected because a for-else loop was “unusual syntax” and therefore considered hard to maintain.
- thiht 4y agoI used one recently in a script and they're definitely not that readable. It always takes some time what "else" means in the context of a loop. I feel like it would work better with a more explicit keyword, but I don't know which one. `nobreak`?
- cpurdy 4y agoI hate the Python syntax using "else" for this, but I love the feature. I've often wanted both a "then" and an "else" from both for and while loops. The "then" would be for a successful completion (no break), and the "else" would be for when the loop doesn't even run a single iteration. But that didn't make it into our "language budget", unfortunately. It's easy to implement, but hard to argue for when it doesn't get used often
- nayuki 4y ago> Quality-of-life features that aren’t too hard to add, and don’t meaningfully change a language in its absence. Often syntactic sugar This is basically the premise of Project Coin, released in Java SE 7: https://openjdk.org/projects/coin/ https://openjdk.org/projects/coin/ The goal of Project Coin is to determine what set of small language changes should be added to JDK 7. That list is: * Strings in switch * Binary integral literals and underscores in numeric literals * Multi-catch and more precise rethrow * Improved type inference for generic instance creation (diamond) * try-with-resources statement * Simplified varargs method invocation
- jonasenordin 4y agoGood observations. Actually more important than it looks, I think. All those little helpful things. Also worth discussing: micro-misfeatures to be avoided when designing new languages. Maybe non-micro-misfeatures, ie the lack thereof, can be considered a microfeature. Like, for example, uniformity. And I just have to trot out my favorite example: Java import statements do not allow keywords and numbers in package names. So we can't put our Java source code in folders named 'import', 'long', or in paths like '2023/01/'. Great. For no good-enough reason - the syntax would actually be cleaner with a separate package name syntax. (BTW, this could be fixed, I think.)
- lamontcg 4y agoRuby having anonymous functions being defined like { |args| <whatever> } and for no arguments you can drop the || entirely. Rust's |args| { <whatever> } with || { <whatever> } being mandatory for no args removes the ambiguity in parsing.
- h4x0rr 4y agoDoes anyone else disagree with kebab case over snake case?
- mncharity 4y agoWebGL's swizzling vector selectors.[1] Where v.x desugars as v[0], v.y as v[1]. Similarly for z and w. Also r,g,b,a. And they swizzle: v.rgb, v.xz, v.zx . So `v1.xy = v0.yx` reflects. [1] https://www.w3.org/TR/WGSL/#vector-access-expr https://www.w3.org/TR/WGSL/#vector-access-expr
- unsafecast 4y agoThat applies to GLSL in general. I tried once to emulate that using C unions, but quickly realized that there's no solution for v.xz, v.xw, v.yw, etc. You can write functions like xyz(v) and that works well enough. Even better if you have ufcs or methods.
- still_grokking 4y agoWhich leads to the question why you would use offset / index syntax instead of dot syntax in the first place. Therefore I would prefer something like this to be the usual array access syntax: val chars = Array("a", "b", "c") val secondChar = a.2 // as a shorthand for `chars.atIndex(2)`, or equivalently `chars.atOffset(1)`, maybe also with `a..1` for the offset case (Also we should stop calling the offset "index", and get a proper "atIndex" method.)
- zem 4y agoI like pyret's dot notation for accessing data associated with variants. from their docs 8<------------ data Animal: | elephant(name, weight) | tiger(name, stripes) | horse(name, races-won) ... end fun animal-name(a :: Animal): a.name end
- KerrickStaley 4y agoKeyword and optional arguments (seen in e.g. Python, Bash with --flags, and OCaml) are my favorite language superpower. They make code more self-documenting and let you add add optional behaviors to functions. This makes it really easy to make concise, highly usable APIs.
- toolslive 4y agoIn OCaml, they are a bit more subtle: let x = ... in some_function ~x if the parameter has the same name on both sides (caller, callee) there's a syntactic shortcut. It's a small but noticeable force that pushes you towards more consistent naming.
- ErikCorry 4y agoToit makes a lot of use of this, and uses the bash syntax.
- tsimionescu 4y agoI love Common Lisp arguments support, where you can also get a parameter that tells you whether an optional or keyword argument was supplied by the caller, instead of relying on the default value, for when you want to know. It's very useful for something like a patch function.
- jameshart 4y ago> Frink has special syntax for date values. You can write # 2001-08-12 # to mean the date 2001-08-12 Frink? Frink? This Visual Basic erasure can not stand. The #-delimited date literal syntax has been found all over the VB family: Visual Basic, VBA, VBScript, and it persists to this day in Visual Basic .NET. Of course, being a VB syntax, it's completely cursed. You can put # 01/05/2023 # in a VB file, and what date it represents will depend on what locale it's.. compiled? executed? evaluated? in? Maybe? Depending on which VB dialect you're in? Good luck. Some of those languages would also accept # 01/05/23 # And they might even agree about what century it's in.
- lillecarl 4y agoWe don't have to follow locale, we could just force ISO 8601 and there won't be any ambiguity.
- rwmj 4y agoYeah, but this is Windows we're talking about. Even the SCHTASKS program (kind of like /usr/bin/at) takes a date which is locale sensitive, making it absolutely useless for scripting. Check out this answer to a question about how to use it: https://stackoverflow.com/a/18730884 https://stackoverflow.com/a/18730884
- lillecarl 4y agoThe language doesn't have to care about $PLATFORM, if the spec says dates in source are ISO 8601 they're ISO 8601 or they're invalid.
- yencabulator 4y agoI think the argument here is that VB is cursed because Windows is cursed; it inherited the bias toward cursedness. Of course other languages can choose to do better.
- catach 4y ago
- CSMastermind 4y agoI really just want every language to support operator overloading.
- BurningFrog 4y agoWe fought that war 25 years ago.
- lamontcg 4y agoYes, `matrix * vector` rather than `matrix.VecMult(vector)`
- pas 4y agojust allow nice infix functions :) (which is allowing nice postfix ones with currying) Scala does it pretty well. and nowadays finally the function names don't require a PhD in ancient Egyptian hieroglyph decoding. so requiring alphanum names for functions is pretty important imho. (sure it's okay if it's just a stern lint warning and the developer has to opt-in. but searching for iteratee is easier than searching for \∆>> or whatever.)
- still_grokking 4y agoScala does a lot right here, but it's supper annoying with its arbitrary limitations for how you can name your methods. If I want a method called `U+1F602`¹ it's not the business of the language to judge that. --- ¹ the actual glyph, which gets filtered out here, also for no reason
- pas 4y agoI think it's okay for a language to help guide its users toward "better code" (of course Rust is the big one for this). But I'm also a firm believer of providing escape hatches. So it should be just a toggle in the project/file/directory to enable whatever behavior. And a very good language would require a human readable explanation for these, so when the developer says allowEmojisInCode = true "we decided to allow emojis to make our happy DSL, see emoji reference at https://..../ https://..../...." downstream users/readers of the code are in a much better position than with just 30000 lines of emojis :)
- culi 4y agoRuby's Enumerable module is incredible and jam packed with features like .tally, .any?, .take, .partition, etc. But one of the things I love most is how seriously they take having their Hash be enumerable. I love being able to loop through any hash as easily as you would with an array
- Semaphor 4y agoBalanced string literals (with some extra QoL) recently landed in C#, haven’t got the chance to use them yet, but they sound really nice in the right situation.
- culi 4y agothis is usually a style thing not an enforced syntax and maybe a hot take but I actually really like leading commas in comma-delineated lists (like Elm and Haskell). Makes changing the order of things really convenient
- mLuby 4y agoAgreed. Especially the more diff-driven development we do.
- still_grokking 4y agoEven better would be to get rid of this annoying syntax noise. Commas in multi-line lists have no use besides making trouble in refactorings and diffs.
- sneak 4y agoFrom perl/coffeescript, i miss until/unless (ie while! and if!), especially combined with postfix conditionals, eg: thing.process() unless thing.cancelled() thing.doOne() until thing.queueIsEmpty() showAdminMenu() if user.isAdmin() etc
- culi 4y agoArrow function syntax
- tlb 4y agoI might add kebab-case to my current language project. From all the code I've written, I only found a handful of - operators not surrounded by spaces, so that ambiguity wouldn't bite me often. Also, I wish the unary negation operator was more visually salient. `foo * -bar` is very different from `foo * bar`, but it's only a handful of pixels on the screen. I've thought about trying to render it as an em-dash or something. Didn't NASA lose a rocket over a spurious - sign?
- harrisi 4y agoNASA reference: https://nssdc.gsfc.nasa.gov/nmc/spacecraft/display.action?id=MARIN1 https://nssdc.gsfc.nasa.gov/nmc/spacecraft/display.action?id...
- chewxy 4y agoAPL uses ¯ for negative numbers. - is a ambivalent function (it can work as a monadic or dyadic function)
- gdwatson 4y agoThere are coding fonts that make the "-" look more like a minus than a hyphen. I know that Iosevka and its variants do.
- int_19h 4y agoSome languages use ~ for negation; wasting it (and other common chars) on bitwise ops is a waste in most languages that don't specifically target bit twiddling. That said, have you considered making this outright illegal without explicit parentheses? I actually wish that more languages would require that any sequence of operators has the same precedence throughout; i.e. a+b*c would also be illegal. It's always a pain to remember the exact precedence rules, especially since they're not consistent across PLs, so I'd prefer any expression that is ambiguous to be explicitly disambiguated.
- NeoTar 4y agoI have a similar opinion on using the exclamation point for the NOT operator. It can be very hard to spot sometimes, especially after an opening bracket - if(!something()) Of course its generally better to try and rename functions or refactor to avoid the negative if possible.
- weatherlight 4y agoSwift and Gleam both have Function Argument Labels and Parameter Name separation. Example in gleam: // definition fn catalog(by list_of_qualities) { add_to_catalog(list_of_qualities) } //applying the function catalog(by: [Genre, Year])
- CGamesPlay 4y agoIf unit testing makes the cut, then I think standardized documentation and doctests should be included also. Python (string literal at the beginning of a class/function), C# (structured comments) and Rust (doc attributes) are three different, valid ways of adding this to the language.
- WalterBright 4y agoD has had these for a long time.
- CGamesPlay 4y agoLooks like these fall into the "structured comments" category, based on seeing /** */ and /// in a repository I found. Does it also have a story for doc tests?
- WalterBright 4y agoYes, tests in those comments are actually pulled out and run.
- ddejohn 4y agoI really adore Python's iterable- and keyword-unpacking operators (*some_iterable, **some_mapping): arr = [0, 1, 2, 3, 4] head, *body, tail = arr # head=0, body=[1, 2, 3], tail=4 head, *rest = arr head, *_, tail = arr *_, tail = arr first, second, third, *rest = arr foo = {"a": 1, "b": 2, "c": 3} bar = {"b": 9, "x": -1} {**foo, **bar} # -> {"a": 1, "b": 9, "c": 3, "x": -1}
- swyx 4y agowhy bother with the distinction between one * and two *? in javascript the … operator neatly does both
- zdragnar 4y agoTechnically, `...` acts as either the spread or the rest operator, depending on the location. I recall there was an initial impression of intimidation among people who were familiar with ES5 syntax when trying to adopt to these new features because of this. On the other hand, I'm fairly certain that having to visually disambiguate between `` and `*` and remembering which did what would have gotten a similar reaction.
- gdwatson 4y agoPython has keyword arguments to functions. In that context, a single star packs or unpacks a list of positional arguments and a double star packs or unpacks a dictionary of keyword arguments.
- gpderetta 4y agoTo complete the description, dictionaries are iterable by key only by default[1], so *dict would be ambiguous if it could splat both. [1] a misfeature, IMNSHO.
- Too 4y agoMaybe more obvious, it also works the other way around. Saving you from doing [head] + body + [tail] or keeping copies of temporary arrays manipulated with append and extend. arr = [head, *body, tail] Same with dictionaries, often very useful when you need to include **os.environ with modifications into a subprocess.
- WalterBright 4y ago> chained evaluators (if 2 <= x < 10) Because C evaluates this to `((2 <= x) < 10)` which is pretty much never what you want, D just makes them illegal. You'll have to add parenthesis.
- ilyash 4y agoComments Section In Next Generation Shell I've experimented by adding section "arbitrary comment" { code here } and this is staying in the language. It looks good. That's instead of # blah section - start code here # blah section - end Later, since NGS knows about sections, I can potentially add section info to stack traces (also maybe logging and debugging messages). At the moment, it's just an aesthetic comments and (I think) easily skip-able code section when reading. Symbols I've decided not to have symbols in NGS. My opinion (I assume not popular) is that all symbols together is one big enum, instead of having multiple enums which would convey which values are acceptable at each point.
- Bilal_io 4y agoYou can do something similar in JavaScript > const love = "love"; > { // Section > console.log(`What is ${love}`); > }
- ilyash 4y agoNot the same ergonomic. The language doesn't "understand" it's a section (no opportunities listed in the original comment).
- zdragnar 4y agoActually, it does, though the only real use is with the `break` keyword for breaking out of a labelled block (or break / continue in a for loop): https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe... Things like stack traces don't track them, unfortunately.
- Beltalowda 4y agoI sometimes do something like: var foo string { // Do stuff // ... foo = "..." } { // Other section... } You can also split stuff up in to sections, but for some kind of functions where you know the functions will never be re-used and are intimately related, I find this clearer. Of course, your language will need to have block scope, or at least blocks.
- vbezhenar 4y agoAbout kebab-case identifiers. What I always wanted is proper spaces! Designing syntax where identifier could have spaces (without backticks or something like that) might be tricky of course. But may be it's not impossible. All those space imitations, whether they're dashes, underscores or camels - they're just imitations. Nothing compares to real spaces. If anything, underscores are closest ones, if you ask me.
- lelanthran 4y ago> What I always wanted is proper spaces! Designing syntax where identifier could have spaces (without backticks or something like that) might be tricky of course. But may be it's not impossible. What would this look like, though?[1] How would you solve the problem of adjacent identifiers vs a single identifier which has spaces? Maybe having identifiers, and only identifiers, starting with a uppercase letter with no uppercase in the rest of the identifier? Then lines like `if MySubRoutine()` is easily parsed as `if My Sub Routine`, and `MyVarType MyVarName;` becomes an easily parser `My var name My var type;`. Looks harder to read than the usual camelCase, kebab-case and PascalCase identifiers though. [1] I ask because I'd like to do something like this when writing a program that comes with it's own language for the end-user to use to enhance the program.
- vbezhenar 4y agoWell, I would imagine that it requires designing a language which ordinary does not allow adjacent identifiers. Of course keywords must not be allowed as part of identifiers (or there should not be no keywords at all like with Lisp). Just an example of my head that I didn't think really much about: function print person (p: person) { var full name = p.first name + p.last name; if p.middle name != "" { full name += p.middle name } print line(full name) for c : p.subordinate person list { print person(c) } } I think this syntax should be parseable with little restrictions (like your identifier can't start with keyword).
- still_grokking 4y ago
- pmontra 4y agoJSON compatibility, to be able to copy and paste from JSON to valid nested dynamic arrays. a = { "a": "a", "b": {"b": 2} } Optional commas at the end of lines, so this is also valid a = { “a“: "a" "b": {"b": 2} } and we are able to swap or append lines without editing the commas or forgetting to do it and get a syntax error. Mandatory commas on all lines would do but it gets in the way of JSON compatibility. This must also be legal code and equivalent to the previous one a1 = { a: "a", b: {"b": 2} } a == a1 # true The developer decides when saving typing time is more important than JSON compatibility. PS: a big yes to kebab-case too. That's in part CSS compatibility because CSS class names are often kebab cased.
- dima_vm 4y agoAbsolutely damned is combination of Kotlin's several features: 1. Lambda functions can be defined with `{}`. 2.`foo(bar, somefunc)` is the same as `foo(bar) somefunc`. In other words, if the last parameter is a function, it can be provided AFTER closing parenthesis. 3. Interfaces that require only one method can be implemented on-side with a lambda function (i.e. `{}` syntax for no-param function). Combined those three features, the code may look like that: routing { static("/statics") { files("css") } get("/foo") { call.respondText("Hello world!") } } So you can make a config-looking file which is just pure Kotlin, with static type checking, autocomplete, suggestions, "this" etc. It's so damned, I'm surprised author didn't mention it.
- plucas 4y agoWhat exactly do you mean by "damned" here?
- sirsinsalot 4y agoI too am confused by the unique use of this word
- brabel 4y agoI am assuming the author is using it as one would use "wicked" (with a positive conotation)?
- benj111 4y agoI don't know why teenagers insist on taking a negative work and making it positive, especially when teenagers don't like adding emphasis to words so you have no idea whether they think it's good or bad. Not that I was completely innocent of this at that age. /Rant.
- cpurdy 4y agoThat's so sick.
- Too 4y agoNested json dictionary lookups with default fallback, for scenarios where any of the sub-dictionaries could be null or missing a key. Write parseDateTime(config["a"]["b"]["c"]) safely as a oneliner. Haven't seen any language solve this in a neat way, without catching indexerror exceptions or ugly chaining of null-conditionals and empty dictionaries as fallback-values.
- hansvm 4y agoIt's not language-level, but I keep a Python class handy that wraps objects like that and has that behavior. You can also access items with config.a.b.c if desired (and if they're valid identifiers).
- pharmakom 4y agoMost of these seem like anti-features to me. They add little expressivity and a while lot of syntax. Maybe the Lisp crowd was right?
- Avshalom 4y agoJust to pop in on kebab case: Prolog has a weird third thing going on. Arithmetic only happens in specific contexts. i.e. A is 4 - 2, % arithmetic, technically is(A,-(4,2)), A is 2 A #= 4 - 2, % arithmetic, A is 2 A = 4-2, % non arithmetic, A is unified with the term -(4,2) which pretty prints as 4-2 A = -2, % non arithmetic but A is the number -2 not a term -(2). A = 4-2, B is 4 + A, % a weird one A is the term -(4,2) but when it gets called in the context is(B,+(4,A)) it gets treated as the arithmetic '-' and B is 6 you can also kebab-case predicate names so l-h-t(L,H,T) :- L = [H|T]. ?- l-h-t([1,2,3,4],H,T). %works as desired H = 1, T = [2, 3, 4]. you can't do it with variables though.
- MrBuddyCasino 4y agoThe "Expanded Parameters blocks" is kind of supported in Kotlin. You can write a function like this: /** * @param arg the string to garble */ fun doThing(@NotEmpty arg: String = "default) In this example, "arg" is mandatory, or else it would have the type "String?", making it nullable. It obviously has a default value. It has an annotation that performs some validation, though admittedly that is a library and not a language feature. And it has its own documentation. I find this more concise than the Powershell example.
- still_grokking 4y agoAs with almost all "Kotlin features" this is a direct rip off from Scala, where the signature would look almost identical (besides the fun keyword).