News for hackers. Stuff that matters.
Re:Magical, Mystical JavaScript Transducers by donut on Saturday June 29, 2019 @12:36AM (#20310831)
Impressive amount of code and words. I think I'd think twice before approving this in a code review, though.

Why is this not the obvious solution to the stated problem?

  function avgPopularity(slang) {
    let sum = 0;
    let count = 0;
    for (item of slang) {
      if (item.popularity > 0) {
        sum += item.popularity;
        count += 1;
      }
    }
    return sum / count;
  }
Re:Magical, Mystical JavaScript Transducers by southerndrift on Saturday June 29, 2019 @03:28AM (#20311288)
Yours is the obvious solution but the problem is a simple example to help people understand the more complex idea of transducers. It's for situations where the code inside the for loop is so complex that it would be nice to organize it with functional programming principals.

The problem with functional programming is that the obvious approach is not efficient since it passes the array several times. So the goal is to make the functional approach as efficient as the imperative for loop.

Now if you do that by hand, you end up with some messy code. So the article shows how you can combine the operations with a helper library in a structured way.

That said, it kind of reminds me of The Evolution of a Haskell Programmer [0]

[0] https://www.cs.utexas.edu/~cannata/cs345/Class%20Notes/10%20...

Re:Magical, Mystical JavaScript Transducers by cousin_it on Saturday June 29, 2019 @06:22AM (#20311773)
For me it's the other way around. A for loop is a general purpose solution that changes continuously with the problem: whenever I need to gather some extra data, just add some hairs to the for loop. The time complexity is obvious, so is the space complexity (how much data is in memory at any given time), and it's easy to pause and debug. But if you have a bunch of FP combinators and recursion schemas, when the problem changes slightly, you have to unfold the whole origami crane and re-fold it carefully again. It's what James Hague called a puzzle language.

The puzzle nature of FP can sometimes prevent the simplest solution to a problem. For example, try writing a function that accepts a list of N numbers between 1 and N and returns its histogram (list of counts of each number). There's an imperative solution in O(N) time with one for loop. But in FP, I'm not sure O(N) can be achieved, and even O(N log N) requires tree-like data structures that aren't needed in imperative.

Re:Magical, Mystical JavaScript Transducers by tomxor on Saturday June 29, 2019 @12:10PM (#20313333)
> just add some hairs to the for loop. The time complexity is obvious, so is the space complexity (how much data is in memory at any given time)

Exactly, when refactoring code the first thing I do is remove all the boxes, create a huge monolithic procedure, then I can see all the inefficiencies, optimise and simplify it, then break it into better fitting boxes (if necessary).

I don't follow the lingo for all the patterns, but ultimately they are usually just different ways of wrapping up things in boxes. I think they are wooden bullets, the most important thing is to not make boxes too quickly, it should be the very last thing you do after figuring out what the code needs to in it's entirety holistically.

I think the bane of most software complexity is actually people being too scared of taming large contexts, so instead they wrap themselves in a hell of spaghetti boxes, just deferring issues and creating inefficiency and obscurity.

Re:Magical, Mystical JavaScript Transducers by ur-whale on Saturday June 29, 2019 @08:31AM (#20312204)
100% agree with you.

I've always been uneasy with FP-style coding for three reasons:

   - you have strictly no idea how your code will be evaluated by the CPU. Some people love that aspect. It makes me immensely queasy. I might be a control freak.

   - as much as I love the idea an cleanliness of composing functions, having to abandon mutability for that is way too hefty a price to pay. There are situations where overwriting memory is the darndest best way to do things. Yes, side-effects are hard to code with, but just like gotos, there are situations where they are the best solution.

   - I've always felt that FP coders are way too focused the beauty of their code rather that the industrial strength of it, which includes: readability, how easy it is to change, efficiency. Proper production code shouldn't be origami puzzles.
Re:Magical, Mystical JavaScript Transducers by ElFitz on Saturday June 29, 2019 @10:28AM (#20312784)
Totally beside the point (which I agree with), but your bullet list renders horribly on mobile devices (lengthy horizontal scrolls >.<')
Re:Magical, Mystical JavaScript Transducers by ur-whale on Saturday June 29, 2019 @11:43AM (#20313202)
I have indeed heard of these "mobile devices" you speak of :p but for some weird HN algorithmic reason, I can't edit my comment anymore ...
Re:Magical, Mystical JavaScript Transducers by aurelwu on Saturday June 29, 2019 @06:56AM (#20311887)
That seems to be such a basic task. Please take it not as me not believing it but could you provide some source about there not being a known O(N) solution for that problem, I'd like to know what the hurdles are and why there might be no solution at all or why finding one is so difficult. (I tried googling it but failed to find something useful)
Re:Magical, Mystical JavaScript Transducers by cousin_it on Saturday June 29, 2019 @07:07AM (#20311913)
The hurdle is that when you're going through the input, you need to update the output out of order. An imperative array can be updated out of order in O(1) time, but FP data structures can't do that. Strict vs lazy doesn't seem to help. I have no source, but I've given this problem to some strong Haskell programmers and they couldn't solve it (without using escape hatches like ST).
Re:Magical, Mystical JavaScript Transducers by mrgriffin on Saturday June 29, 2019 @11:16AM (#20313035)
As a professional Haskeller who solves numerical computation problems I wouldn't call ST an escape hatch. You're right that I can't think of a "pure" way to compute a histogram, but I doubt anyone uses Haskell specifically to prevent all mutations but rather to carefully control where mutation can occur[1]. I'd wager referential transparency is "good enough purity" for almost all tastes.

[1] Of course we have plenty of other reasons to use it, but I digress.

Re:Magical, Mystical JavaScript Transducers by setr on Saturday June 29, 2019 @08:33AM (#20312214)
https://old.reddit.com/r/haskell/comments/3bqlis/how_do_you_...

Found a decent discussion on the matter. Main issue at hand is that its not really FP in question, but datastructures, and more specifically, how far you extend immutability semantics.

In this case, if you forgo immutability requirement, you can trivially mantain semantic purity while still updating the simple array. But with immutability, you can’t construct an array, so you’re locked behind log(n) datastructures

Re:Magical, Mystical JavaScript Transducers by ur-whale on Saturday June 29, 2019 @08:21AM (#20312162)
Because of the whole immutability dogma of FP languages, you can't do this simply in a clean FP style:

    ++(histogram[sampleId]);
which is the heart of a simple histogram computation.
Re:Magical, Mystical JavaScript Transducers by philjohn on Saturday June 29, 2019 @08:04AM (#20312103)
The fact that it creates multiple intermediate arrays is a sign of the bad design in js ... and why (IMHO) if you want to do functional programming, sticking to a functional programming language can be a better option.
Re:Magical, Mystical JavaScript Transducers by z3t4 on Saturday June 29, 2019 @07:19AM (#20311944)
FP works very well in short simple examples. If the for loop would be any more complex the FP solution would probable be incomprehensible. Optimizers however love small immutable and steteless functions so FP would likely be faster then the imperative version. For example by making it run parallel, caching, inlining, etc
Re:Magical, Mystical JavaScript Transducers by layoutIfNeeded on Saturday June 29, 2019 @09:28AM (#20312442)
>FP would likely be faster then the imperative version

[citation needed]

I highly doubt that even the most sophisticated JS engines would produce faster machine code from the functional spaghetti than a simple for loop.

Re:Magical, Mystical JavaScript Transducers by Gormisdomai on Saturday June 29, 2019 @06:37AM (#20311830)
Imo replies here all miss the point.

The reason to use transducers instead of a for loop here is that it allows you to expose a library function which takes a transducer as input. It's hard to refactor the for loop above to allow someone consuming this function to specify additional things they want to aggregate due to an API change in the definition of the 'slang' type, but with transducers you just take one as an argument.

Re:Magical, Mystical JavaScript Transducers by dan-robertson on Saturday June 29, 2019 @01:33AM (#20310957)
Because a bunch of those lines are concerned with the boring mechanics of how to compute this thing rather than what is being computed. It’s reasonable to say having a big system of composable transducers is pointless for one computation. It’s harder for 1000.

This point isn’t about transducers specifically but more about avoiding specifying the things you don’t care about. Eg, in Common Lisp (which was old enough to somewhat care about how to iterate things):

  (defun avg-popularity (list)
    (loop for item in list
      when (plusp (popularity item))
        sum pop into s
        count t into c
      finally (return (/ s c))))
This avoids having to care about the mechanics of how to sum or count things and I think it’s too sequential, when you don’t really care about that. One can certainly imagine a simpler to express solution in e.g. apl.
Re:Magical, Mystical JavaScript Transducers by TeMPOraL on Saturday June 29, 2019 @04:26AM (#20311452)
Note that to make it correct Common Lisp, you'd write it like that:

  (defun avg-popularity (list)
    (loop 
       for item in list
       for pop = (popularity item)
       when (plusp pop)
       sum pop into s
       and
       count t into c
       finally (return (/ s c))))
Two changes: 1) making `pop' be a thing, and 2) `when' clause of loop only applies to the next clause by default (here, `sum pop into s'), you need to include `and' to chain it with the next one so that both are guarded by `when' condition.
Re:Magical, Mystical JavaScript Transducers by agumonkey on Saturday June 29, 2019 @03:19AM (#20311268)
The article obfuscates the point. Reducers/transducers are from the FP world. In FP avoiding mutable state is one the main point.

    dot = field => obj => obj[field]                        // unsafe
    Array.average = self -> reduce(add, self) / self.length // unsafe
    slang.filter(s -> s.popularity > 0)
         .map(dot('popularity'))
         .average()
Bonus points:

    - no state
    - reusable pure functions
    - a tad shorter
    - maybe as readable as the `for over state` idiom ? (depending on habits)
Re:Magical, Mystical JavaScript Transducers by chris_st on Saturday June 29, 2019 @08:17AM (#20312149)
Downside: Still going over the array multiple times.
Re:Magical, Mystical JavaScript Transducers by sli on Monday July 01, 2019 @03:09PM (#20328685)
You could (usually, but not always) compose the functions you're passing into filter and map and use reduce instead to do both operations in a single pass.

(Edit: This is a big point in the article -- apologies, I hadn't finished reading it yet.)

Re:Magical, Mystical JavaScript Transducers by agumonkey on Saturday June 29, 2019 @09:03AM (#20312346)
fair point, in js it will, in other languages that idiom gets deforested into a single pass though
Re:Magical, Mystical JavaScript Transducers by chris_st on Saturday June 29, 2019 @06:03PM (#20315074)
Cool, which languages do this?
Re:Magical, Mystical JavaScript Transducers by cofunctor on Saturday June 29, 2019 @06:30PM (#20315211)
This ought to work with any lazy language (or lazy data structure), which is one of the huge benefits of laziness for FP.
Re:Magical, Mystical JavaScript Transducers by sooheon on Saturday June 29, 2019 @03:18AM (#20311265)
Of course trivial toy examples demand simple answers. But as you add more processing (partitioning + further operations on partitions, take every nth, stop when some predicate is true...), transducers let you build each in isolation and compose them easily. Your obvious solution might start to get a bit strained, and the code for any single process in the chain can't be reused.
Re:Magical, Mystical JavaScript Transducers by dheerajvs on Saturday June 29, 2019 @02:37AM (#20311119)
Nitpick: There should be a check for zero count to avoid a divide-by-zero. It's missing in the original article as well.
Re:Magical, Mystical JavaScript Transducers by ec109685 on Saturday June 29, 2019 @06:43AM (#20311852)
Why isn’t NaN the right result for the average of an empty set?
Re:Magical, Mystical JavaScript Transducers by ec109685 on Saturday June 29, 2019 @06:26AM (#20311784)
Your solution requires that slang be fully populated upfront, while the article shows a solution that can operate on a stream of data, an item at a time.
Re:Magical, Mystical JavaScript Transducers by layoutIfNeeded on Saturday June 29, 2019 @07:26AM (#20311969)
False. It can just as well be a lazy iterator that returns data one by one from a stream.
Re:Magical, Mystical JavaScript Transducers by serpix on Saturday June 29, 2019 @09:28AM (#20312444)
because there is dirty mutation and it relies entirely on side effects to work. (this is sarcastic, that is exactly how one should go about this one example case.)

It however is a completely different thing when longer chains of filter / map need to come along and the true power of transducers is needed.

In clojure I've had to use transducers at least three times in the course of the last four years!

Re:Magical, Mystical JavaScript Transducers by psadri on Saturday June 29, 2019 @12:40AM (#20310849)
Amen.
Re:Magical, Mystical JavaScript Transducers by edjrage on Saturday June 29, 2019 @12:50AM (#20310873)
because something something mutable state
Re:Magical, Mystical JavaScript Transducers by bjoli on Saturday June 29, 2019 @03:53AM (#20311367)
Transducers in theclojure sense often carry hidden mutable state. This is a solved problem for languages with either heavily optimizing compilers (the atria transducers by ableton for c++ are pure and with visible state) or by type system magic (Haskell, but there you should just use conduits).