functional-programmingramda.jstransducer

Why do I get an error when I use transduce?


I am still new to functional programming and have been trying to learn how to use transducers. I thought I had a good use case but every time I attempt to write a transducer with Ramda for it, I get the following error:

reduce: list must be array or iterable

I have tried rewriting it several ways and looked at several explanations on the web of transduction but to no avail. Any suggestions?

const data = [{cost:2,quantity:3},{cost:4,quantity:5},{cost:1,quantity:1}];
const transducer = R.compose(R.map(R.product), R.map(R.props(['cost', 'quantity'])));
const result = R.transduce(transducer, R.add, 0)(data);
console.log(result)

Solution

  • In the context of a transducer, compose reads left to right. You just need to invert product and props:

    const data = [
      {cost:2,quantity:3},
      {cost:4,quantity:5},
      {cost:1,quantity:1}];
      
    const transducer = 
      compose(
        map(props(['cost', 'quantity'])),
        map(product));
    
    console.log(
    
      transduce(transducer, add, 0, data)
    
    )
    <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>
    <script>const {compose, map, props, product, transduce, add} = R;</script>