7 ms·
Numbered block parameters in Ruby
- scotty79 3y agoNumbers feel hacky. Rust's tuple.0 feels hacky.
- ezekg 3y agoI personally love Rust's tuple syntax. I wish more languages allowed [0] as .0.
- block_dagger 3y agoI too was not thrilled to see the “_1” style in Ruby. I avoid it.
- personalityson 3y agoArrays start at 1
- tomschwiha 3y agoWe should have started arrays with -2147483648.
- ketzu 3y agoWith wrap around! -2147493649 is the same as 2147493646. This is true even if your array has more than 2^32 elements. Also, 2147493647 is reserved for special use!
- mdtrooper 3y agoKotlin has a lot useless syntax sugar, for example @decorators are less powerful than the @decorators in python. And How do you say the opposite of sugar syntax in English? Because my lovely rustlang has a lot of sigil chars as old Perl, it makes me sad.
- adql 3y ago> And How do you say the opposite of sugar syntax in English? Syntax spice ? It burns when you eat/read and it burns when you write/poo > Because my lovely rustlang has a lot of sigil chars as old Perl, it makes me sad. I unironically prefer Perl mess, at least you don't have macros and annotations generating who-knows-what at random parts of code. I mean, not that you couldn't in Perl, there is plenty of horrid things you can do using some more obscure Perl's features (my favourite so far was modifying other package's package-scoped variables), but most code in Perl doesn't.
- valvar 3y agoBoilerplate
- throwaway17_17 3y agoI’ve thought I had usually seen syntax salt be used as the opposite of sugar. I know there is some university’s PL Theory lecture guides that use it, just can’t think of where it is. edit —- I just checked, and salt is ‘name dropped’ in the Wikipedia article for syntax sugar, and there were a few more links making me think it is relatively common.
- aragonite 3y agosyntactic broccoli. The idea behind 'sugar' is 'tasty but inessential', so the strict opposite would be something essential but not so tasty. But maybe 'syntactic thorns' correspond better to the sense you intend to express.
- matsemann 3y ago> Kotlin has a lot useless syntax sugar, for example @decorators are less powerful than the @decorators in python. I think you're comparing two different things. Kotlin has "annotations", not decorators. It's because of it's java inheritance, where that is the way it's done. It's two different concepts. With a decorator, your code is replaced with a function call with the function itself as a parameter. With an annotation, you're just adding metadata and an annotation processor or static analysis tool etc can do whatever it wants with it. Like aspect oriented programming. You mark your code as having certain properties, and then other code can find it and react to those. I don't know of much other useless syntactic sugar in Kotlin? I think most of it is quite nice, for instance how you can put the lambda outside parenthesis or create infix operator for more readable code. I also like the implicit `it` parameter in lambdas, better than what this article shows. Doesn't support multiple arguments, though.
- adql 3y agoDid the author of the feature missed Perl or something ? Perl does that with few thing, like regexp captures. It's kinda sorta neat for writing shell oneliners but that's about it. But then concise and intelligent design wasn't ever Ruby's forte.
- frou_dh 3y agoThats not a very "intelligent" response to the article because it goes into detail about benefits the author sees in concision and communicating intent in normal code.
- kmac_ 3y agoWell, Perl died because it's syntactically too sweet.
- vidarh 3y agoThis is ironic given just how much of this syntax Ruby has lifted straight from Perl. Including $1 etc. for regexp captures, and a litany of other "$" variables. If anything, those parts of Ruby's design tend to be among the aspects most often maligned, and we have to excuse it with "Perl did it, blame Perl". Ruby is in many way the unholy offspring of Perl and Smalltalk. And I mean that mostly in a good way, but it also gave us warts.
- quirino 3y agoI would love for C++ to have more concise lambda syntax. Having to write [](int x, int y) { return x*y } even for the simplest lambda is a pain. Rust's syntax looks ideal: |x, y| x*y. Haskell's is also sweet. For my own purposes I've defined macros so that I can write L1(x+5) or L2(x*y) (the x and y are hardcoded in). Not elegant but it keeps me sane.
- ketzu 3y agoPersonally, I mostly want a more ergonomic way to write lambdas that I find more pleasant to type and read, even if it is as 'verbose'
- gpderetta 3y agoyou can get '_1 * _2' to work. Whether you want to is another story :D More seriously, even something like "(x,y) => x*y" would be nice. edit: I forgot that I managed to make the $(x, y)(x*y) syntax work a few years ago when trying to emulate constexpr lambdas: https://github.com/gpderetta/libtask/blob/master/lambda.cpp https://github.com/gpderetta/libtask/blob/master/lambda.cpp
- duped 3y agoPersonally I don't think closures need any additional syntax, just reuse function definition syntax and implicitly capture its context based on variable usage. I also hate the name "lambda" because it feels intentionally confusing and special. It's just a function that captures some context.
- nneonneo 3y agoBoost.Lambda (https://www.boost.org/doc/libs/1_62_0/doc/html/lambda.html https://www.boost.org/doc/libs/1_62_0/doc/html/lambda.html) is probably what you want, and even predates the introduction of proper lambdas into C++! Here’s a few simple examples cribbed from their documentation: // Set all elements to 1 for_each(a.begin(), a.end(), _1 = 1); // Print elements separated by spaces for_each(b.begin(), b.end(), std::cout << _1 << ' '); // Sort in reverse order sort(c.begin(), c.end(), *_1 > *_2);
- the_af 3y agoThe title is unfortunate: it seems like TFA will argue this syntax is indeed useless, while the article actually explains its rationale and comes to the conclusion it's quite useful. It's unfortunate because readers on HN are already responding to the title instead of to the content...
- kshahkshah 3y agoTFA?
- chrisshroba 3y agoSome context on the acronym (which typically stands for "the fucking article"): https://news.ycombinator.com/item?id=19781756 https://news.ycombinator.com/item?id=19781756
- johndunne 3y agoInteresting… the first time I’ve come across a useless acronym.
- dchftcs 3y agoI guess the more useful and original one is RTFA, and TFA is a derivative that gets used sometimes.
- johndunne 3y agoThat makes more sense, RTFA.
- michaelteter 3y agoAnd RTFM predates that one. Read the f manual is a common reply to basic questions about tools and commands in Linux.
- the_af 3y ago
- FFP999 3y agoSpeaking as one of the eight people to ever write Elixir professionally, this was a small ergonomics feature that I really got to like (along with the `|>` pipe operator).
- hackyhacky 3y agoI understand the author's position, and despite its usefulness, I think the numbered arguments are an inelegant solution. In Haskell, by way of comparison, any one-parameter function can be used as the argument to map: ghci> map reverse ["hello", "goodbye"] ["olleh","eybdoog"] is (mostly) equivalent to the more verbose form with an explicit lambda: ghci> map (\s -> reverse s) ["hello", "goodbye"] ["olleh","eybdoog"] Operators are just normal functions, but tuples are not automatically uncurried. Here I'm using the multiply operator (*) to multiple a list of pairs: ghci> map (*) [(1,2), (3,4)] ERROR ghci> map (uncurry (*)) [(1,2), (3,4)] [2,12] Points-free syntax can be used to construct chains of operations without any explicit lambda variable. Here filter strings of more than two characters: ghci> filter ((>2) . length) ["a","bb","ccc","dddd"] ["ccc","dddd"] In lambda syntax: ghci> filter (\x -> (length x) > 2) ["a","bb","ccc","dddd"] ["ccc","dddd"] I find the Haskell syntax concise and clear, and I always miss it when using other languages (despite Haskell's other shortcomings). Edit: formatting
- jerf 3y agoCurrying is fun and I miss it sometimes as well, but as near as I can tell, it is essentially immiscible with traditional languages. I've seen so, so many attempts, and they are so, so bad. Surprisingly few attempts even seem to get over the bar of understanding what currying is, and why it isn't just partial application. Now, I am not too concerned with which is "better" or anything, nor do I much care for pedantry for the sake of pedantry, but in this case it's a matter of type signatures; curry(some_function) and partial_apply(some_function, param1, param2) are fundamentally different type signatures and for that reason, not because of abstract verbal purity or something, aren't the same thing. I mean, right out of the gate you have the problem that in most conventional languages you're looking at your first example being map(reverse)(["hello", "goodbye"]). Whether Ruby syntax could be bent into making it work without parens (or Perl perhaps) I don't know but with all the other things going on in those syntaxes I'm sure it would be quirky as can be, possibly quirky beyond practical usefulness. And in dynamic scripting languages you'd be looking at a lot of actual function calls, so performance is going to be trashed if you use this pervasively.
- 3y ago
- kshahkshah 3y agoI try to optimize for the reader of the code who didn't write it who has to maintain it, which often feels like myself a year after I crack back open the file. From that perspective, I don't love _1. Basically I don't want to have to dereference things when possible, I want a direct reference. My working memory is not large, etc. I'm not sure I see the value of ".then"... the one-off variable names on the side make it easy for me to scan quickly and understand what is happening w/o having to procedurally view the right side of the assignment. If you want to ensure that these vars are truly one-off, wrap it in a block or method. I don't think Ruby's syntax needs to evolve. I just wish the core team cared more about opening up the lang to the improvements which were being offered by e.g Chris Seaton (RIP) and his colleagues. I wish typing proposals were being hotly debated etc. I'm sad that after 20 years I don't really want to use Ruby or Rails going forward despite how incredible the ecosystem really is, mostly because the data science, typing, and FE integration story is weak now.
- Syntaf 3y agoAs someone who loved rails, got a job writing typed python, then tried to go back to rails, the lack of typing really kills me. I never realized how _nice_ it can be to have types in a dynamic language, even if they’re just annotations. To be fair though Ruby is a much much harder language to wrangle under types than python.
- pawelduda 3y agoYeah I tried it a few times and there was usually pushback during code review. I agree though, saving a few characters is not worth the readability you lose vs even something like `users.map { |u| (...) }`
- kubectl_h 3y agoWe outlawed it immediately via Rubocop but I use it all the time in IRB. We also don't allow single letter variable names. I'm an old school rubyist and find this to be an annoying constraint that can't be auto-corrected so it adds a little friction to writing code but arguing for more terse code is always a losing proposition so I just deal with it.
- pawelduda 3y agoYes, in repl it's convenient. I don't mind single letter block var names if the block spans one line :)
- toxik 3y ago`ii` it is then
- billyruffian 3y agosigh, I once encountered a PFY junior who named all variables some variation on `nx`, so `n1`, `n2`, `n99` because they 'were all just numbers'.
- toxik 3y agoUsing `i`, `j`, and `k` as index variables is not bad practice.
- billyruffian 3y agoWell, my attempt at a humorous aside didn't land. To be strictly serious we are talking about block parameters in ruby which contain the values yielded to it which, in an enumeration, is likely to be a value object from a collection and only occasionally an index (where you've explicitly chained `#with_index` for e.g.). If you are nesting deep enough in ruby to call for `k` then, yes, it would be bad practice.
- lifthrasiir 3y agoRaku [1] deserves a honorable mention where it has named anonymous parameters, written as `$^x` and ordered lexicographically. In my taste as a PL enthusiast, the biggest problem with this kind of anonymous parameters is a conflict with nested blocks. Suppose that our fictitious language is expression-oriented, `{ |x| ... }` denotes an explicit closure, `{ ... }` denotes an implicit closure and `$1`..`$n` are anonymous parameters in them. Consider the following examples: { $1 + $2 } // Yeah, that would be `{ |x, y| x + y }` {} // Is this a zero argument function? { $100 } // Does this have 100 arguments??? { |x| $1 + $2 } // Maybe this should be invalid... { { |x| $1 + $2 } } // But maybe this should be okay?? { { |x| $1 + x }($2) } // And same to this??? { { |x| $1 }($2) } // Uh... { { $1 }($2) } // Should be same to above, but... { { $2 }($1) } // Not this (and will fail)! The problem is much worse when you don't even have an explicit boundary like `{ ... }`. A limited form of automatic function, say `_ + _` without no parentheses, might work, but anything beyond that quickly devolves into a mess. [1] https://docs.raku.org/language/variables#Variables https://docs.raku.org/language/variables#Variables
- gpderetta 3y agohttps://en.wikipedia.org/wiki/De_Bruijn_index https://en.wikipedia.org/wiki/De_Bruijn_index
- jzimbel 3y agoElixir puts some guardrails on its numbered-argument anonymous function syntax, which I think do a good job of restricting its use to defining extremely simple functions. 1. The function has to use all of its arguments at least once. You can’t do `&(&2)`, because it skips the first argument. 2. Single-expression. You can’t do something like `&(x = &1; x + 1)`. 3. No nesting. You can’t define an additional anonymous function inside of a & expression, or even use a `&SomeModule.some_fn/arity` capture. For anonymous functions with nesting, you have to use the `fn arg1, arg2, ... -> body end` syntax.
- mcphage 3y ago> One is tempted to ask here: what would be conditions/language changes so we could’ve just written this? > serialize :salary, format: -> csv_currency(_1) > I didn’t analyze this deeply, but “intuitively” this seems enough syntax for the interpreter to understand “the next code is one-statement lambda’s body.” I believe that Swift has an @autoclosure attribute which allows this?
- michaelteter 3y agoAnd Clojure has their way of handling unnamed variables in anonymous functions. ;; Single argument (fn [x] (* 2 x)) #(* 2 %) ;; Multiple arguments (fn [x y] (+ x y)) #(+ %1 %2) ;; Remaining arguments (fn [x & args] (reduce + x args)) #(reduce + % %&) Example copied from this nice page - https://silviapan.com/blog/anonymous-functions-clojure/ https://silviapan.com/blog/anonymous-functions-clojure/
- RodgerTheGreat 3y agoIn K, you can write a lambda with an explicit argument list: {[a;b]a+b} But if you leave it off, the names "x", "y", and "z" implicitly refer to the first three arguments, and their presence controls the valence (arity) of the lambda. {x+y} / a lambda with two arguments {y} / also a lambda with two arguments, discarding the first Using the implicit names for short definitions is highly idiomatic. By removing an unnecessary degree of freedom, it increases the likelihood that two K programmers will arrive at identical formulations of a short piece of code.
- jacknews 3y agoIt's not just useless, but actively harmful. Especially when reading code, there's yet another special syntax form to learn, and one which has no real utility to structure the code better or to better communicate it's intent and/or operation.
- dragonwriter 3y agoKind of dubious even of the “useful” example toward the end, which can be rewritten without _1 nearly as succinctly as: ENV.fetch('CONFIG_PATH') .then &File.method(:read) .then &YAML.method(:parse) .dig('metadata', 'created_at') .then &Time.method(:parse) Really, if we want more compct syntax sugar for this, letting .:<identifier> be shorthand for .method(:<identifier>) would probably be better than _1 for this circumstance and more broadly useful for making functional-style programming more concise in Ruby.
- zverok 3y agoWell, first of all, I was one of those who fought for method references as first-class objects for a few years (the story is told in my blog before[1]), and "let Ruby eventually become more functional" was one of my main arguments! That being said, there are a few problems on this road, that make it less probable to be followed. First, as Ruby doesn't have first-class Method objects (e.g. object corresponding to `File.method(:read)` doesn't exist until you call `method(:name)` explicitly), this style being popularized will either bring a lot of subtle performance problems, or will require redesign of Ruby's internals. Second, if we'll make an example _a bit_ more complicated, say: ENV.fetch('CONFIG_PATH') .then { File.read(_1, encoding: 'KOI8-U') .then { JSON.parse(_1, symbolize_names: true) } .dig('metadata', 'created_at') .then { Time.new(_1, in: CURRENT_TIMEZONE) } ...it would be impossible to rewrite with `method`, until currying would be signficantly improved (currently it can only be applied to first arguments, not tail ones, and even then looks horrible). So it is not impossible, and it is a turn of the language I'd like to see in the future, but it is not as straightforward as I once imagined. 1: https://zverok.space/blog/2022-01-13-it-evolves.html#taking-offense-for-method-references https://zverok.space/blog/2022-01-13-it-evolves.html#taking-...
- Lammy 3y agoI love these and use them constantly :)
- ezekg 3y agoI'm also a big fan: https://github.com/search?q=repo%3Akeygen-sh%2Fkeygen-api+_1.&type=code https://github.com/search?q=repo%3Akeygen-sh%2Fkeygen-api+_1...
- Lammy 3y agohttps://github.com/search?q=repo%3Aokeeblow%2FDistorteD+_1&type=code https://github.com/search?q=repo%3Aokeeblow%2FDistorteD+_1&t... here
- hk__2 3y agoIf the author is around here, could they explain their use of <blockquote>s? They appear to be used to introduce comments inside the text, but that’s really a confusing markup.
- zverok 3y agoUgh, never thought about that this way! I believe it is a habit back from my journalistic days, when there were "insets" besides the main text with "things that deserve mentioning here, but kinda out of the main flow... but more related to it than footnotes." I miss the richness of markup of paper magazines! Does it harm the reading experience significantly?
- Kerrick 3y ago<aside> would be appropriate for that use case in HTML.
- toasterlovin 3y agoSeems like allowing arbitrary names for the variables would have been the sweet spot between concision and explicitness. So: things.each { puts _thing } pairs.map { _x * _y } It's kinda insane, but in the beautiful way that Ruby is.
- munificent 3y agoTangential but: > My homegrown theory is that the idea of array.each { ... } as the main syntax for cycles was the first “aha!” of the new language development for its author > The style that flourishes with this new shortcut is representing computation as a chain of small blocks, declaratively describing transformations from inputs to outputs. The style that is native to Ruby, the first mainstream language to have enumerable.transformation { ... } as the main cycle construct, and, I believe, played a role in normalizing “map”, “reduce”, and “filter” as a way of thinking about how things are handled. Matz got that from Smalltalk. That's why most of the enumeration methods in Ruby match the names of similar methods in Smalltalk ("collect", "reject", "select", etc.) and not the corresponding names in functional languages ("map", "reduce", "filter"). The "each" method is the odd one out because that's called "do" in Smalltalk and "do" is a reserved word in Ruby. Smalltalk definitely isn't mainstream today, but it did have its day in the sun where it was one of the better-known languages.
- zverok 3y agoYeah, should've mentioned that probably (though a post is already a mess of footnotes, aside notes, and parenthicals). I do believe though that a lot of modern languages got that from Ruby (or, via Ruby, from "JS that Rubyists wrote" and such), when it was a "hot new thing" for a brief moment in 2000s. Or maybe it is my skewed perspective.
- dragonwriter 3y ago>That's why most of the enumeration methods in Ruby match the names of similar methods in Smalltalk ("collect", "reject", "select", etc.) and not the corresponding names in functional languages ("map", "reduce", "filter"). Ruby has both, actually; "map" is a synonym for "collect", "reduce" is a synonym for "reject", and "filter" is a synonym for "select" (well, actually, they are both synonyms for "find_all"). And the non-Smalltalk names seem to have had more influence on newer methods, e.g., Enumerable has filter_map, but not select_collect, even as a synonym.
- zverok 3y agoRuby didn't always had both. `reduce` as an alias for `inject` was introduced in Ruby 1.8.7; `filter` as late as in Ruby 2.6 (just a few years ago, and most of the codebases I saw are still preferring `select`). Yes, the dictionary is normalized in the last years towards what became industry/mainstream standard names for the concepts, but the statement that initial names were derived from Smalltalk is correct.
- ejlxsh 3y agoI can't imagine writing something like this while also serving in the Ukrainian Army as an active soldier. The 'Irks and Quirks' of Ruby would seem much less important to me in that position!
- frizlab 3y agoI’m surprised Swift’s `$1`, `$2`, etc. weren’t mentioned in this article.
- milliams 3y agoWhy, if Ruby has zero-indexed arrays, do the arguments start with _1?
- Alifatisk 3y agoThis issue explains the change from _0 to _1 https://bugs.ruby-lang.org/issues/16178 https://bugs.ruby-lang.org/issues/16178
- psychoslave 3y agoI don’t know Scala, and found interesting the way each occurrence of the anonymous determiner refers to the next item in the sequence. I’m not fan of using underscore for this however. I think that a new reserved word worth the clarity it brings. For example "thither"[1], "thilk"[2] or even "said" (as in aforesaid) or "such" are both rare enough to lower possible collision in existing code bases, and explicit (you only have to discover it once at worst) to make a good trade of, to my mind. [1] https://en.wiktionary.org/wiki/thither https://en.wiktionary.org/wiki/thither [2] https://en.wiktionary.org/wiki/thilk https://en.wiktionary.org/wiki/thilk [3] https://en.wiktionary.org/wiki/said#Determiner https://en.wiktionary.org/wiki/said#Determiner