66 points · by ingve · 10y ago · 84 comments
The C++ implementation of this notion looks like an inscrutable, complete trainwreck, like the rest of the language.
Transducers separate out the transformation processes into free-standing composable functions. This makes the transformations first-class values, and makes it possible to apply such transformations to less collection-like entities such as async channels.
I'm personally still not sure if it's a good idea or not, but it is an interesting approach.
Iterator adaptors take an iterator (which usually, but not always, comes from a collection, e.g. "my_vec.into_iter()") and give you another iterator back, without allocating an intermediate collection; the iterator itself stores only the current state of the iteration process. You can apply iterator adaptors to such iterators as the receiving end of a channel ( http://doc.rust-lang.org/std/sync/mpsc/struct.Receiver.html#... ), and you can pass around the iterator and add other computations to the end of it before you "run" the whole thing.
However, I'm not sure what you mean by the transformation processes being functions. In Rust these processes (iterators) are values, and have methods that produce a derived process by appending a step; for a concrete example:
let fb_chars = "foobar".chars(); //fb_chars is an iterator
let not_o = fb_chars.filter(|&x| x!='o'); //not_o is an iterator; we got it by applying the filter iterator adaptor
for i in not_o {println!("char: {}", i);} //run the iterator with a for loop; we could also have run it by calling .collect() and obtaining a collection
What are the domain and range of the functions you mention in Clojure?Well that's pretty cool and iterators are generic, but not generic enough. If you'll look closely their protocol has certain constraints. For example the next() call is synchronous. If the next element is not ready, well, tough luck, the current thread needs to be blocked. Another constraint is that iterators produce elements, right? Well, iterators are cool and useful, but many operators like map(), filter() and flatMap() can be applied on things that don't necessarily produce values. As a side note, this is why monads are hard to understand, being a little more abstract than iterators.
What transducers from Clojure are doing is to define a more generic protocol (more generic than that of Iterator) such that you can have defined operators, like map and filter, operate on whatever you want, such that you can reuse the implementation of those operators. You can also compose those operators, before applying them to something concrete.
Clojure transducers are different because a transducer is a function which accepts a reducing function and returns a new reducing function, adding behavior by how the input function is composed into the result function. Because the domain and range of transducers are both reducing functions, they can be chained through function composition. A chain is actually applied by transforming a reducing function then using that function to `reduce` (Rust `fold`) a collection.
The cool part is that the transformations don't refer to collections at all, not even through some highly abstract collection-like interface. This makes them applicable to other domains, like the previously-mentioned channels.
Like https://doc.rust-lang.org/std/sync/mpsc/struct.Receiver.html (scroll down to the trait implementations)?
Clojure used to have (/is deprecating) what you're describing. It's being replaced by transducers to avoid having to implement the same functionality whenever there's a new paradigm/idea. I.e this week we're doing lazy seqs, the next CSP or streams - the transducer logic stays the same.
AFAICT, iterator adapters don't require you to reimplement the "transducer logic" any more than transducers do. You implement a transformation into an iterator (eg. IntoIterator) and from an iterator (eg. FromIterator) and use the standard transformations on the iterators.
Since a transducer is like an iterator adapter, one is comparing these to functions Iterator<A> → Iterator<B>, which can be passed around and reused as first class citizens with no more difficulty than any other object.
I'm not sure, but one difference might be that you can't give a chunk of stuff to an iterator adaptor and say "run as much of this as possible, and then suspend". Iterators are inherently pull-based, so instead you say "I want X values". I can imagine the former being more useful in some cases where the producer is deciding when computation should be performed.
They take a stream of values (i.e., an iterator, which is really only enough state to produce the stream, but not an actual collection of the values produced by that stream) and give you a different stream back, e.g. one that looks like the original stream with a function applied to each element or certain elements removed. Rust iterators are "lazy", and iterator adaptors maintain this property.
Transducers don't have this problem.
When you call next on an iterator, you expect it to give you the next value or to tell you that there will be no more values. It's not supposed to give you no value 'for now' or many values. With a transducer it can change your destination value in any way it likes according to your final reducer function.
Perhaps it's better to say that iterators are controlled by their destination and so are used in a pull fashion while how reduction functions are used is defined by the source so can be used in push mode. It's easy to emulate pull mode with a push source - you just keep pumping values into one end until one comes out the other, but you can't emulate push with a pull destination, as you can't tell without running your adapters how many values will need to go into the pipe to produce your next value.
Imagine you have an event source, and you want values coming out of it to go into some other data structure as they arrive via the same kind of chain of transformations as you might use on a simple data structure. It'd be pretty ugly to do this with iterator adapters (probably have to have an iterator stream of futures, but then you can't do a normal map/filter, etc.), but the reduce on the event stream can pump values through as they come in, regardless of if any of them ever make it to the end of the pipe.
Yeah, we get it that functional languages came first, but rather than looking down on C++ why not celebrate that functional constructs are making it into places where they haven't been before.
Because that's a meaningless thing to celebrate? Having functional concepts available in a poorly integrated way, with super ugly syntax is more depressing than anything, because seeing it in use is a reminder of how much cleaner it would be in a language like Haskell or OCaml.
Why not accept that C++ isn't a functional language, and realize that many die-hard C++ users won't use these features for the same reasons they're not already using functional languages.
I'd rather see these efforts directed towards improving the compilers and libraries for languages like Haskell, OCaml, etc.
I swear I remember fans of older OO languages saying the almost exactly the same thing with "object oriented" in place of "functional" about the way C++ grafted OO concepts onto C when C++ was new -- and, IMO, with good justification. Still, C++ was not exactly unsuccessful with that, either.
I'm a die-hard C++ user, and have come to love functional programming for a very C++y reason: improved performance that comes from lock-free parallelizability (if you never modify values, you don't have to synchronize access).
But I also love the simplicity that comes from not having to think so deeply about lifetimes and which portions of code can see which objects in which states. The abstraction of data-structure from algorithm is nice, the terseness is nice, the regularity is nice, but it's the lifetime and visibility simplification that helps me the most.
I don't know Haskell or OCaml. I wouldn't know a monad if it slapped me in the face. But functional C++ makes me happy
Operating Systems. Games. Deterministic soft and hard real-time systems (there's a reason you wouldn't be able to certify a control system for a fighter jet written in Javascript). Scientific stacks. Multi-media (do you think Renderman is written in Ruby?).
I'd even argue against using GC'd languages in desktop applications. It's getting to a point where these run-times are gobbling up a few gigs worth of pages from the OS and they still hang or crash when the OS decides to start paging them to disk. Or another process gets priority from the scheduler. The fact is while processor speeds have increased memory hasn't and that's the big bottle-neck on current hardware. Despite popular beliefs I think users do care about performance. They don't notice good performance but as soon as that beachball/whitescreen/whatever comes up and the UI is unresponsive you can bet their face is scrunching up like a walnut. Does that happen only to 1 or 2 users? 10%? We don't measure things like that enough when our happy little GC will take care of it for us.
Tuning GCs for workloads is probably as much or more work, in my limited experience, as designing your program from the bottom up around its specific data patterns. You'll get better performance from the latter approach more often than tuning a GC to your workloads after profiling. The wins in that case are incremental (we tuned our JVM after some profiling and shaved off 1.8% from our inner loop!). Where they can be dramatic with the right data structures and careful attention to locality (we saw an 800x reduction in cycles due to cutting unnecessary allocations and a 300% speed increase -- sweet!).
Even tuning your allocation strategy can net you bigger gains than trying to structure your code around a JIT.
All that being said -- GC's are incredibly useful in many situations. You just have to measure and be thoughtful. Memory is still an issue GC or not.
To me that's any device with a battery(I'm looking at you smartphones), gamedev, and as you mentioned embedded systems.
There's also another class of programs that's not related to GC. C++(and C by subset) is the only way to write truly cross-platform code for all the modern OS's. If you want to target Android, iOS and Desktop C++ is the only supported path on all those platforms with the right performance guarantees(JS doesn't cut it perf-wise on mobile, yet). That's why you see DropBox and quite a few other shops using C++.
There is at least work towards making controlled GC pauses a possibility.
It's so far from the mainstream norm to implement these ancient time-savers that you can't help being excited about Swift, even though such a language should be mundane by now.
How so?
The crazy thing is that, to me, some new features of the language feel like they are being pushed because [x] language has it more than the actual need to solve a particular problem that was to difficult to solve using only the constructs available previously.
Two nights ago I was at a C++ Meetup and this guy was explaining how to solve this problem using a crazy-complicated pattern with a new proposed C++ feature. Eventually I had to stop him and ask him why we could not simply do this with a priority heap, a threadpool and some semaphores (simple shit). "Oh yeah, you could do that, too, but this way is cooler".
Right now we're using Knockout but it's feeling a bit grumpy in various respects so I've been looking into React. But still it is common to have breaking changes, and then there's the whole ES5/ES6/TS split.
I need something that our devs can do a Google search "How do I do <X> in <Y>" and nearly copy-paste the result. Knockout has been particularly good for that because it's evolved very slowly and every example for it is in ES5.
Microsoft has wedded themselves to Angular for ASP.NET 5, but it looks like it's Angular 1. Meanwhile Angular 2 looks much better but again splits across ES5, ES6, TS, and Dart... If someone searches "How do I do <X> in Angular?" who knows what combination of assumptions might be unlying that answer.
As much as I'd prefer to use something like React, I think shops with the combination of lower skilled staff and longer term maintenance projects (like ours) will need to wait until, hopefully, the industry calms down and settles on a set of new standards.
Microsoft seems to have gotten sucked into the "do everything a million different ways" spaz attack with ASP.NET 5, but meanwhile Apple seems to be doing it right with a narrow, opinionated set of technologies with a well understood evolutionary path and specific tools for specific jobs.
On the one hand, it's great to new attempts to compose algorithms mushrooming, but on the other hand it would be great to see more aligned efforts to collaboratively push forward the TS and its implementation.
[1] A technical specification (TS) can be thought of as a self-contained mini standard that vendors can implement, but do not have to in order to be "standard-compliant". A is a promising candidate for future inclusion into the standard, however.
See Appendix 1 and 4.
(It's not exactly what you're asking for, but showcases that such claims often hold true in practice.)
No templates, but standard maps, sets, arrays. Both compiled and interpreted. No virtual functions. Clean, simple syntax close to C, but with all the nicer stuff C++ brought along, like lambdas.
C++ is industrial-strong, but sometimes it seems it's not taught because it's too expert, in favor of java or C# while C/C++ is the language that should be taught.
I don't understand languages like rust and go which introduce a non trivial new syntax. Why not keep the C flavor ? I don't see how people are going to adopt languages like that. There should be a statically compiled language which has the same philosophy of python.
I don't understand what having "the same philosophy of Python" has to do with not keeping "the C flavor". The delta between Python's syntax and C's syntax is basically equal to the delta between Go's syntax and C's syntax, or Rust's syntax and C's syntax.
About the deltas, maybe you're right, but I disagree about the difficulty of the languages. For example go function prototypes seem pretty heavy to fully grasp and understand. Rust also have expert programming facilities and paradigms.
it does nothing special or novel whatsoever - except maybe to set a quality bar for writing unmaintainable code.
the very first example given is simple, but demonstrates a thorough lack of understanding for what constitutes readable code. if i had to code review this from a junior i wouldn't let it go in without significant changes, and i'd make time to teach them some of the most basic concepts about producing maintainable and readable code... but only because its easier than firing them.
i am skeptical that the label 'transducer' has any solid value whatsoever here. i can understand the concept... its basically to encapsulate stages of algorithms neatly. the fact that it manifests one way in Clojure says nothing about the value of using exactly the same mechanism in C++ to achieve the same...
normal classes, normal functions, and not being rubbish at writing code combine to give a much better result for the same class of problems.
The pros were that, at least for my limited testing, performance was essentially equivalent, for optimized code, between the transducer implementation and the equivalent hand rolled code (e.g., doing a map+filter transducer vs. a foreach with an if), and that using transducers offered further optimizations if you applied them completely up and down the stack, by allowing you to, say, early terminate a sequence that would otherwise have been done in entirety behind some opaque function call. I don't really consider code readability to be a benefit here since transducers are, somewhat inherently, a heady subject.
You can see my work here: https://github.com/AndrewGaspar/transducers.hpp
I haven't done a formal write-up or anything on it, but check out the tests if you want to see what consuming them would kind of look like.
EDIT: One of the things I'm proud of was rigging it, without need of dynamic typing, such that a transducer could produce heterogeneous types. Obviously your sink would need to be capable of accepting all these different types being produced by the transducible process, but it allowed for some interesting integration with <iostream> - say, creating a transducer that inserts comma's between integers for output (see https://github.com/AndrewGaspar/transducers.hpp/blob/master/... and https://github.com/AndrewGaspar/transducers.hpp/blob/master/...).
EDIT 2: I notice that early termination was not shown in this blog post. I implemented this by essentially introducing a known wrapping type (https://github.com/AndrewGaspar/transducers.hpp/blob/master/..., sorry I know it's a bad name). The trick with this was I only wanted the returned values of a transducible process to be wrapped by this struct (since it has the overhead of one bool value, and a check to actually determine if it could early terminate) if a single transducer in the chain can early terminate. It also made each individual transducer slightly more complicated to implement, unfortunately.