108 points · by ashvardanian · 1y ago · 112 comments
Yeah, this would be std::reverse_bind() or something.
The more you know :susface:
This is enough to determine it is written by Chatgpt.
If you're not familiar with Chatgpt, ChatGPT finds its roots in advanced machine learning research, particularly in the field of natural language processing (NLP), where it leverages deep learning models like GPT (Generative Pretrained Transformer) to understand, generate, and interact with human language based on vast amounts of data and context.
On the other hand, I remember reading it and thing it was a bit-flip operation since it's in <functional> instead of <tuple>. So I was quite surprised to find that it's really much more like a tuple operation (which is template magic) than bit flipping (at runtime, or possibly also constexpr)
(ugh, it is unnerving how certain my expectation is that the answer will start with "you're absolutely right!")
The two missing pieces are -
* structural pattern matching
* uniform function call syntax that is : a.foo(b) vs foo(a, b) being interchangeable.
With the kitchen sink approach of design I’d not be surprised if these get into the language eventually. These ideas have been proposed a few times but haven’t been seriously considered as far as I know.
Herb Sutter has proposed this: https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2023/p30... (twice, even, there was an older version of the paper several years ago that didn't pass).
I'm resolutely opposed to such a thing because, having had to actually wade through C++'s name lookup and overload resolution rules in the past, they're a dense, confusing morass of logic that you can only stand to stare at for a half-hour or so before your brain turns to mush and you need to do something else, and anything that adds to that complexity--especially in "this makes things two things nearly equivalent"--is just a bad idea.
(For an example of C++ overload resolution insanity, consider this:)
// Given these overloads...
void f(std::float32_t);
void f(double);
// Which one does this line call? Assume float/double are standard IEEE-754 types.
void f((float)1);You can try it yourself on godbolt all the way back to GCC 3, test(float x) has always emitted movss and test(double x) will result in movsd/movlpd.
Based on the history of C++, they will, but with extremely bizarre syntax. Instead of a.foo(b), it will be something like a@<foo>::&{b}.
Out of "respect for existing deployments," the syntax must accommodate the relic even though no one has seen it outside of the folklore of one 1993 Usenet post.
Every tool chain will begrudgingly implement it and then years later when someone proposes removing it the counter argument will be, "we can't remove it now someone is using it!" The someone, of course, is a hobbyist on the mailing list whose project depends critically in the feature.
For three decades, many people have said "C++ is nearly usable, except for just one thing..." Many of those people have gotten their way, which is why C++ is now a kitchen sink of mutually inoperable, poorly thought-out features, like someone implemented the entire index from Journal of Programming Language Design.
If you don't believe me, check out the implementation of `flip` at the end of the article. Over a hundred lines of templates, variadic parameters, constexpr, r-value references, parameter forwarding, default and explicit constructors, and other things that, imho, simply should not exist in a modern programming language.
So, instead, I'd say the best thing for C++, and the world, would, at this juncture to stop adding features.
flip :: (a -> b -> c) -> b -> a -> c
flip f x y = f y x
A little better, I'd say. Note that the first line is the type signature and is technically optional.EDIT: and if that's too exotic for you, here's the solution in Python.
def flip(x):
return lambda *z: x(*reversed(z))Ive written a lot of c++ in the past but I'm not particularly knowledgeable about fp, so I'm wondering why this is important. Is it syntactic sugar or something more significant?
Think of a fluid API, but instead of chaining method calls you'd pass data to several functions "chained" together similar to how UNIX pipes work.
With this type of API, you can pass one argument into the function and pipe the other such that:
data |> foo(bar) |> baz
Is a more FP friendly version of: return baz(foo.bar(data)) data |> bar(foo) |> baz
Or maybe: data |> bar(&foo) |> bazdata |foo> bar |> baz
This almost gets us to a point where you can express a dataflow DAG in code.
Still, it’s always fun to stumble on corners of the STL I’d never paid attention to, even if I won’t end up using them. Thought it was worth sharing :)
https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2025/p26...
Yes, but that has to come with proper sum types. std::variant doesn’t quite cut it.
I’d also absolutely require a simpler lambda syntax. The current one is terrible for one-liner lambdas.
Now the question is : what can we improve in the language so it can allow you to define a sum type better and more usable compared to std::variant?
This is a surprisingly difficult question to answer, hence we haven’t had progress there.
Then why is the language so ridiculously complicated? I had the most fun working with it back in around 2000, and even then it was quite insane. A lot has been added since then.
Except all the OOP features, which absolutely needed dedicated syntax even though they could have been a library.
s = someobj()
ref1 = s.doOne
ref2 = s.doTwo
// then later
ref1(arg1,arg2)
ref2()
In Java you need to code like a crazy to have similar results. Also m = someclas.doThree
// later
o = someclas()
o2 = someclas()
for i in [o,o2]:
m(i)
so many patterns done easy and the right wayProbably because the use case for it with higher arity is hard to imagine. (Indeed, TFA gives only examples with binary operations.)
> Fortunately it is not just useless knowledge either: flip can be reified at will by copying the following C++17 implementation.
> [snip 114 lines of code]
Meanwhile, in Python:
def flip(f):
return lambda *args, **kwargs: f(*args[::-1], **kwargs)
(I leave keyword arguments alone because there's no clearer semantic for "flipping" them.)The `toolz.functoolz.flip` implementation (being restricted to binary functions) is an even simpler one-liner (https://toolz.readthedocs.io/en/latest/_modules/toolz/functo...), though accompanied by a massive docstring and admittedly simplified through a heavyweight currying decorator (which accomplishes much more than simply getting a function that does the right thing).
#include <functional>
constexpr auto flip(const auto& f) {
return std::bind(f, std::placeholders::_2, std::placeholders::_1);
}
The best I could get the fully general version is still pretty obtuse though: // std doesn't have a template version of placeholders::_1, _2, etc., so we need to
// define our own.
template <int I> struct placeholder{};
template<>
template<int I>
struct std::is_placeholder<placeholder<I>> : std::integral_constant<int, I> {};
// flip must be an object so that the function type can be deduced without needing
// to explicitly specify its parameters' types.
template<typename F>
struct flip {
const F f;
// operator() deduces the argument types when the flip object is called, but really
// all we need to know is the number of arguments.
template<typename... Args>
constexpr auto operator()(Args... args) {
return bind_reversed(std::make_integer_sequence<int, sizeof...(Args)>{})(args...);
}
private:
// a helper function is needed to deduce a sequence of integers so we can bind all
// the placeholder values.
template<int... Is>
constexpr auto bind_reversed(std::integer_sequence<int, Is...>) {
return std::bind(f, placeholder<sizeof...(Is) - Is>{}...);
}
};But if you want to flip the 2nd and 3rd argument in Haskell it can be done by flip itself:
flip23 foo = (\x -> flip (foo x))
In Smullyan's "To Mock a Mockingbird", these combinators are described as "cardinal combinator once/twice/etc. removed", where the cardinal combinator itself defines flip.
The C++ code has no overhead and is equivalent to a compile time transformation.
* Some standards such as ISO 6709 (Standard representation of geographic point location by coordinates) describe points as (latitude, longitude).
* Others such as RFC 7946 (GeoJSON) describes points as (longitude, latitude).
Using (hypothetical) std::flip to reify these APIs seems like a loaded footgun - someone is bound to accidentally use it {zero, two} times to convert between orders when it needs to be used once and wreak havoc.Geographic points should probably be represented as a labeled structure to prevent confusion and passed into functions as such. Using two separate libraries with mutually incompatible error-prone APIs as described is the real loaded footgun IMO. If you can't find better libraries, write wrappers; if you don't have time to write/maintain wrappers, pray. Anything else is just a bandaid.
That risk is inherent to the problem at hand, and has nothing to do with std::flip.
The way to turn that into an even wronger solution is to create a helper just_apply(function, lat, long) that passes the arguments to the function in the (hopefully unique) order that successfully works; so flip if needed, based on function’s type signature.
The governing standard for geospatial data representation is ISO 19125, which defines (longitude, latitude) order. GeoJSON naturally conforms to ISO 19125 since it is a format for processing data on computers.
ISO 6709 is essentially a print formatting standard and orthogonal to storing geospatial data on computers. That some data file formats happen to be human readable does not make ISO 6709 apply.
If you are processing geospatial data on computers the correct order is always (longitude, latitude).
The Lisp family doesn't provide anything but parentheses, maybe lambda (not necessarily under that name) and a whole lot of heated arguments.
Only specific dialects of specific Lisp-family languages provide, or don't provide this and that:
TXR Lisp:
1> (mapcar [flipargs -] '(0 1 2) '(10 20 30))
(10 19 28)
flip is called flipargs because flip is the name of an operator that mutates a place with a negation of its current value: i.e (flip x) means (set x (not x)) with x evaluated once. flip :: (a -> b -> c) -> b -> a -> c
flip f x y = f y xCan you write a Haskell version that works for functions with any number of arguments?
The C++ std::flip from the article, however, reverses the order of all parameters. Reproducing that in Haskell would require fancy type-level programming or compile-time metaprogramming, both of which would defeat the simplicity of my initial version.
I hope not.