0

I am new to functional programming and I can't find a function like reduce to build an AgreggateRoot given an EventStream:

List.reduce ((aggregate, event) -> aggregate) eventList

As I understand the reduce function only works with parameters of the same type of the output

  • Generally you'll use something like map to transform arguments so they're of a consistent type (if I understand your question) – Telastyn May 30 '19 at 23:59
  • No, I want the reduce function but the total parameters must be of another type than the element – Leonardo Mangano May 31 '19 at 0:04
  • 2
    Are you using the term "Aggregate Root" properly? – Robert Harvey May 31 '19 at 0:11
  • Yes, you transform the parameters so they match your aggregate (or in the other order if you want the result to differ from the aggregate) – Telastyn May 31 '19 at 0:39
  • @RobertHarvey I think yes. i.e. I have the Aggregate Root Customer and I have to rebuild it based on its events – Leonardo Mangano May 31 '19 at 21:06
2

You are probably looking for fold. The main caveat with a fold is it requires you to provide an initial value for the output, instead of using the first element, but this is usually what you want when the output type is different than the elements.

| improve this answer | |
  • This is the right solution. I tough that fold produce an output of the same type of the elements. Thanks – Leonardo Mangano May 31 '19 at 21:00
  • Fold can also be used to produce an output of the same type as the elements, and frequently is. – Karl Bielefeldt Jun 1 '19 at 6:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.