some_array.do_thing().do_another_thing().do_something_else()
versus
do_something_else(do_another_thing(do_thing(some_array)))
Note the first example could be an example of chaining - where each function returns "self" and we progressively transform the object. Or it could be simply each function returning different values which are operated on. Either way, the pattern is usually cleaner and easier to debug than the nested equivalent.
some_array |> do_thing() |> do_another_thing() |> do_something_else()
Even though Elixir is functional and aggressively not object oriented, if you squint at this pattern you get the readability of an OO-style method chaining API.
See also:
https://mamememo.blogspot.com/2019/06/a-brief-history-of-pip...
``` 1.. |> take 10 |> map {|e| e2} |> (x) ```
which is equivalent to
``` (1...).take(10).map{|e| e2} ```
So in order to use it you still need extensions on every single object. The only reason that looks nice is because in this example you continuously call methods on lists that return a list. You can't add `my_custom_list_operation(list_input)` in between.
Going forward, the pipe operator is going to be showing up in many new languages. I've used elixir a lot, and the pipe operator is a genius piece of syntactic sugar.
some_array
|> do_thing()
|> do_another_thing()
|> do_something_else()"string".do_stuff() - do_stuff() is a method on the "string" class, with all of the potential gotchas that might come with an OO implementation. Does the method mutate the internal state of the object? Does the particular class override the default implementation? Is it a monkey-patched implementation (the issue raised by this article)?
"string" |> do_stuff() - do_stuff() is a standalone pure function. The data is immutable and does exactly what it says.
a.this().that() requires that a.this() returns an object on which .that() can be invoked.
(that (this a)) requires that (this a) returns an object that is a suitable argument to that.
Ruby syntax apparently is especially nice if you know Japanese: https://flatironschool.com/blog/ruby-and-the-japanese-langua...
(do_thing . do_another_thing . do_something_else) some_array
Are we talking about Ruby? Because it does.
It has both:
(do_thing >> do_another_thing >> do_the_last_thing)[arg0,…,argn]
And: (do_the_last_thing << do_another_thing << do_thing)[arg0,…,argn]
(Where the things in the composition are procs/lambdas, the closest thing Ruby has to functions as distinct from methods.)I wasn't thinking specifically of Ruby (and indeed I don't know Ruby, nor was I aware that it has this kind of support).
Rather, I was thinking about programming languages in general, since the top-level comment seemed to be talking about the general principle.
Out of 5 languages I use on a regular basis, only one of them has _some_ support for function composition. But even then, not as flexible as what you're demonstrating here. So my point is that across programming languages, the chaining approach is generally more readable than the composition approach. And that in turn favours methods over global functions.
If I ever start using Ruby, I would probably be on the fence about which approach is better though.
Which, believe it or not, they still teach function composition as good old g(f(x)) in high school algebra...
(do_something_else . do_another_thing . do_thing) some_arrayThat Ruby also implements X.foo().bar().baz() is a weird thing about Ruby that can be very powerful, but is unrelated to the dot syntax.
I feel like roughly half of Ruby programmers treat it as "Lisp but better", which leads to confusion about the OO aspects of the language.
Admittedly I don't think anyone really prefers the second way of writing it, but that's not the same as being ecstatic over the first one.
For example, in C, the array operator is mostly synthetic sugar for pointer addition, and could be removed. Should it be removed? Of course not, cause programmers are not thinking of pointer arithmetic when indexing an array.
And as much as I love lisp, it's one of the top reasons none of them ever had widespread adaption. Nobody likes having to do math like this (* (+ (sqrt 4) 2) 4).
And because of easy macros (another advantage of the syntax), you can easily add syntactic sugar as you see fit where you care.
Some languages (like C# and Rust) support extension methods, so you can use method-style to invoke separately-defined procedures. But in other languages, method-style APIs become an inextensible privileged zone, and I personally prefer to minimize the number of inherent methods as much as possible. By preferring direct-style invocations, I avoid the temptation to stick a useful method on the class itself "for convenience".
Or for quick and dirty debugging, with print statements, being able to put a println in the middle of any method call, just by adding a .also{println(it)} to the chain.
Isn't the D solution actually that:
A.B(...)
is syntactic sugar for: B(A,...)
if A.B() is not specifically defined.(Yours both flips the elements and reverse the direction of sugaring, as I understand it.)
In the second example, we have only function application. Put a breakpoint or print statement into do_another_thing and it is sure to go off.
(do_another_thing could support OOP dispatch as a generic function. A generic function is still something that is called first then dispatches methods based on its arguments. E.g. in Common Lisp we can (trace do-another-thing) to trace the calls.)
I just don’t understand why Python thinks it necessary to define global functions for something that naturally should exist as a method.
And, of course, there’s no way to know up front when to use a global function vs when to use a method.
len(my_list)
is just sugar for my_list.__len__()
if you feel strongly about the convention: https://docs.python.org/3/reference/datamodel.html#object.__...And for other unary "magic methods", the disconnect can be even bigger. E.g. iter(x) is not just a synonym for x.__iter__() - it can also produce an iterator for something that only provides __len__ and __getitem__.
In the Ruby way, with otherwise similar setup, you would have a mixin that provided __iter__() given __len__() and __getitem__(), and classes that had the last two but wanted the behavior of the first would just include that mixin class as a parent, rather than having a separate branch in iter() to handle the different cases. (Ironically, its one way that Ruby is less TMTOWTDI than Python is.)
Python does have such a mixing, it's collections.abc.Sequence https://docs.python.org/3/library/collections.abc.html#colle...
somestring=somearray.join(' ')
Versus Python's: somestring=' '.join(somearray)I don't use either Ruby or Python but I think that the first way is more natural.
foldLeft(tail(array), str(head(elem)), (acc: String, elem: T) -> acc + ',' + str(elem))
Which makes the array method easier to understand than the string method. Funny how I thought it was _obvious_, but you find the opposite obvious. 1 ",".join(["a", "b"])
2 ["a", "b"].join(",")
3 ",".split("a,b")
4 "a,b".split(",")
These method names feel like active form so 1 and 3 should be correct but it's 1 and 4 despite "a,b" obviously is not splitting "," but it's splitted by itIn Ruby it's 2 and 4.
I'm out of luck twice but at least Ruby has a and b always to the left and the comma always to the right so I always remember it.
print('Hello '.join('world!'))Very often, when I'm learning new code, there's one line I'll write over an over in console bindings:
> some_object.methods
It provides a super-easy way to learn what methods are actually relevant to `some_object` without having to pour over every method available in the global namespace and figure out whether `some_object` is a valid argument to each. You can also apply set logic like `some_object.methods - {}.methods` to return only the methods available on `some_object` that AREN'T on typical objects, which is a very, very, very powerful learning/exploration tool.For example,
irb(main):003:0> PaypalService.methods - Service.methods
=> [:create_prepay_invoice, :build_client, :capture_invoice_funds, :get_order_info, :get_plan_price]
Side note: you can also call `.source_location` on any method to see exactly what file/line it's defined in (even in core ruby/rails methods). There's a lot of other inspection methods available to learn more about objects and what you can do with them, which IMO is a benefit over your latter example.It's this great ease of introspection that makes Ruby so fun.
It's a pretty trivial matter, so I wouldn't go breaking encapsulation everywhere just to support it. D has a feature called Universal Function Call Syntax where a.f(b, c) is sugar for f(a, b, c) for any free function, rendering those issues moot. I just wish more languages would pick it up!
I really don't see what chaining via methods bring that simple function composition doesn't.
Visual flow from input to output.
(Ruby can compose either way, so you can build a pipeline of procs in flow order, but if you aren’t chaining the input still goes at the end, not the beginning.)
My ideal preference is for a language to support universal function call syntax where x.f(y) is equivalent to f(x,y) always and also include support for custom operators (or at least include common functional operators).
Ruby has composition operators in both directions:
given:
x = 2
f = lambda {|a| a+1}
g = lambda {|a| a*2}
the following are all equivalent: f[g[x]]
(f>>g)[x]
(g<<f)[x]
What’s inconvenient is that to use it with methods, even ones that can be invoked in ways that look like function calls in other languages, you have to realize a method object, since method names don’t name objects. Or, as Matz says (I don’t think of Ruby as a Lisp at all, but in this context it makes sense) Ruby is a Lisp-2, not a Lisp-1. 2.g.f
g(2).f
(g >> f)(2)
(f << g)(2)
with a strong preference for the first one. That's the Elixir pipeline with a dot instead of a |>The second one is OK-ish but it turns weird with a long list of functions.
The last ones are not nice to read, too much syntactical overhead.
There is a ton of new syntax added to Ruby in the last years and they had to find a way to fit it into the space between what was already there. The results are not always nice IMHO.
They’ve been among the methods for invoking procs since at least Ruby 1.8 (2003); there are several – all of these are equivalent.
f[x]
f.(x)
f.call(x)
f.yield(x)
> I’d like to write one of: 2.g.f
g(2).f
(g >> f)(2)
(f << g)(2)
Ruby is a pure OOP language, and “.” is the syntax for method invocation. So its really not available as a composition operator. So the first two don’t work for that reason. Further extending Ruby’s syntax to make unmodified parens both invoke methods and serve as syntax sugar for .call() on objects would probably be problematic (that’s why “.()” was adopted.)> There is a ton of new syntax added to Ruby in the last years
None of the stuff related to this except the composition operators is added recently. And those aren’t really syntax, just normal operator methods added to the Proc class.
The latter is in the global namespace (or you have to create a module/namespace for it). The former is encapsulated in a class. Encapsulation is nice.
I think a lot of these debates come down to repl development versus ide development. I’ve done a lot of both, but many complaints come down to people on one side not understanding the way the other side works.
No, it doesn't.
Pervasive OO style and monkey-patching core classes are orthogonal. Ruby favors the former strongly, and supports the latter, and Rails rather heavily leverages the latter (to the extent that it has been harshly criticized for it by much of the non-Rails Ruby community), but there is no necessary relationship between them.
How do code completion work in languages where the predicate goes before the subject?
When declaring a variable, in a typed language you could use the variable type to filter down the possible function completions based on return type; in practice, I don't think any LSPs do that.
And, sure, I guess you could `Array.has_my_thing(some_array)`... but that's just re-arranging the mixin structure behind `Array`. It only looks different until you start peaking under the hood.
IMHO, sometimes you want a function because in your problem domain there's a universal (or universal enough) act/question/etc, and sometimes you want a member function because in your problem domain the act/question/etc only makes sense given some particular context.
That depends on the implementation. A monkey-patch is definitely problematic, but when it's properly scoped, like C# extensions, Rust Traits or Ruby Refinements, it's quite elegant.
Because of that, you can not have 2 parallel versions on the same lib, in the sane app, not possible. You load classes once, and they are accessible everywhere, magic! No need for loader headers as in JS, Python, Java, Go, ...
That said, ruby devs like to have "sane" extensions like to_json. People proffer to write "@object.to_h.to_json" instead of "JSON.parse(@object.to_h)" and not to think about loading json lib. I agree that Rails is abusing this too much.
with the very latest ruby version, you actually can:
https://rubyreferences.github.io/rubychanges/3.1.html#kernel...
Kernel#load: module as a second argument
(the link jumps to some random place for me)Well, you always could, it was just a bit more involved:
So, I think it's fair to say that the advantages you are lay out are more tangible than the other side of the trade-off.
Having written too much Ruby code I'd still cringe every time I have to pass the array.
Edit: To make it actually clean it should be 'MyArrayLib.has_my_things(array)'. Still really dislike it despite all the logical arguments for it.
my_thing.in?(some_collection)
since it affords the object agency to decide for itself.For some
method(thing a, thing b) thing {
return a * b
}
is not better than method
a * b
end
If you're an "artist" type that care about the aesthetics of your code you tend to prefer the second.one of the reasons i prefer python to ruby. sorted(my_thing) will sort anything that can be sorted. no need for monkey patching -- you just call it and, if it can be sorted, it will be sorted.
Python does the exact same thing, it just hides it from you using ugly __methods__ that the language itself will call by convention. What determines sortability? "Anything that can be sorted" just means anything that implements the __lt__ method. In Ruby, this method is called <=> and the Comparable module builds upon it.
You can add iterators with __iter__, reversed() calls __reversed__, etc.
The difference is that most likely that CPython and CRuby started with different capabilities to map native implementations into the language.
The biggest difference between the two is python adds more functions into the global namespace, while Ruby pushes pretty hard to encapsulate logic within types.
To be sortable, you collection has to be a collection, and it has to have comparable elements. That has to be provided by the type itself.
The difference between Python and Ruby is how to add more functions. If you make a library to sort collections (or format phone numbers), the Ruby way is to monkey-patch collections (or numbers). Whereas the Python way is to offer a free function that takes an iterable (or number). This is what we are discussing.
Of course Python classes have methods.
Iterables use functions like __len__ and __next__. The with keyword is just a thing that implicitly calls __enter__ and __exit__ on a context management object.
The discussion has mostly been about instance methods defined in classes, and how do you define “like sort” in this claim?
list.sort() is a method in Python; it's the equivalent of Array#sort! in Ruby.
To that I reply that no, there is no method to sort hidden in __methods__. This is not how functionality is added to classes in Python. If you want to add something that works on all iterables, you don't insert new methods in iterable classes, like you do in Ruby. That free-standing sorted() function really is a free-standing function, it is not actually a method "hidden in ugly __methods__".
You don't in Ruby, either.
If you want something that works on all Enumerables, you normally write an (instance or class/module) method on some other class or module that takes an argument that supports the methods provided by the Enumerable API.
(In Python, you might do this or write a bare function, but Ruby doesn't have bare functions; it's possible to make proc objects in a library which is the nearest equivalent, but you’d almost never do that, because module methods are much more convenient.)
In either Python or Ruby you might also monkey-patch existing classes to add functionality to the., and this is slightly more common in Ruby than Python, but because Python iterable, unlike Ruby Enumerables, don't have a common superclass that isn't shared with non-iterables, you couldn't easily do a “for all iterables” thing in Python [0] by monkey-patching because you don't have a good target to monkey-patch, whereas in Ruby you might do something for (nearly, because duck typing is a thing and it's possible someone could build an enumerable by implementing the whole API without mixing in the module) all enumerables, not by adding methods directly to individual enumerable classes, but by monkey-patching the Enumerable module itself.
The main difference here is that Python (despite having support for mixins because it uses multiple inheritance) tends in it's core to use a mix of OO public APIs and procedural public APIs built on top of OO protocols using (often dunder) methods, rather than either consistently-OO or consistently procedural APIs, whereas Ruby is consistently OO and uses mixins to provide shared functionality building on a narrower protocol where Python would use a suite of functions. (Python tends to be more OO in its stdlib and third party libs than in its core, except specifically when supporting protocols defined in the core and consumed through built-in functions.)
[0] except by monkey-patching object with code that tries to use the dunder methods that underlie the iteration protocol and fails if they don't exist, but while theoretically possible I don't think anyone would do that.
Your point about Ruby syntax not really being meant for free functions is well-taken though.
sort() in ruby is declared on Enumerable. Sorted() in python is declared to take an iterable first parameter. They are pretty much equivalent, except python has built-in functionality to reverse the order of the output array, while ruby you would have to negate your sort function.
Ruby however allows types to override sort, such as when the underlying type is a red black tree which is already sorted. For duck typing, you can also declare a compatible sort method on types which do not implement Enumerable - doing so in python would require a separate method.
array.sort # returns a new collection
array.sort! # sorts in place
(Ruby convention is to add a ! when methods directly modify the object they're called on.)No, Ruby convention is to add a “!” when there is a “less safe” version of an operation, for which a “more safe” version exists without a “!”.
Mutating versions of methods where a nonmutating version also exists are one common example, but not the only one, and mutating methods without a nonmutating counterpart don't get “!”.
Awhile back I gutted the code and ripped out 60% of it, including all the monkeypatching and the maintanence burden on every ruby release dropped sharply.
(And I'm assuming we're talking about the more polite kind of Monkeypatching where you're adding methods to global classes that are net-new, not the practice of opening up a class and scribbling over methods that you didn't write and replacing behavior, where should you should always mental picture your SemVer contract being lit on fire)
IME you don't usually do monkey-patching, although there are circumstances where it makes A LOT of sense (usually test suites). It's one of those sharp knives - safe if you plan out using it, dangerous if you don't.
some_array.has_my_thing() is better than has_my_thing(some_array). ?
The former, the extension has so many issues, it messes up namespacing, it's unclear where it came from, etc. etc. The latter is just a function. It's not longer, or complex, it's just more straightforward. I really think things where you extend or override built in types is almost always just a bad idea, because the alternative is almost always just as concise and doesn't confuse everyone.