0

In Scala, I would like to ensure that a lambda is associative.

For example, I imagine adding an annotation or extending a trait, then concrete implementation would be tested using reflexion.

But I would like to have the opinion of people more experienced in functional programming. Maybe there is an existing way to do that, or maybe this is something that can be ensured by construction. I just want an automatic way to ensure or check that at compilation to avoid any possible error for fold and reduce.

  • 3
    Is impossible to be sure at compile time that any operation is associative. However, you can just request a `Semigroup` from **cats** which by convention has to follow the law of assossiativity. – Luis Miguel Mejía Suárez Jun 09 '21 at 04:41
  • Thanks @LuisMiguelMejíaSuárez, it totally makes sense. Do you know a good way to check that fold and reduce associative operation is always written with |+| ? I can't find an easy way to do that with plugins like scalafix. – Terry BRUNIER Jun 09 '21 at 06:53
  • What you can do is rather write your own extension method that doesn't accept a function, but rather just the `Semigroup` _(either implicitly or explicitly)_ and then you may write a rule that Forbids the use of the original method, that way you force everyone to use the extension method instead. – Luis Miguel Mejía Suárez Jun 09 '21 at 12:46
  • What do you mean by "write a rule that Forbids the use of the original method"? Concretly, is it some code to write? – Terry BRUNIER Jul 29 '21 at 00:41
  • I meant a **Scalafix** rule, but that was just an idea. I don't know if that would be possible at all, and how would it look like. – Luis Miguel Mejía Suárez Jul 29 '21 at 00:51
  • It's impossible (or at the very least, very hard) to prove that an operation is associative completely automatically. It's better to simply tell people to check if it's associative or not themselves rather than write a compile-time proof checker or something. – user Aug 08 '21 at 22:38

0 Answers0