1
$\begingroup$

I am writing a function to find the intersection between two sets.

The non-functional requirements of the assignment include avoiding "side effects".

function intersection(a, b) {
 return helper(a, b, []);
}
function helper(a, b, c) {
 if (a.length == 0) {
 return c;
 }
 if (b.contains(a[0])) {
 return helper(a.slice(1, a.length), b, c.concat([a[0]]));
 }
 return helper(a.slice(1, a.length), b, c);
}

Would mutating the argument c in the above code be considered a side effect?

The specific assignment is written in OCaml, so, though the above example is in an imperative language, I want to stay true to the spirit of functional programming.

Please don't provide any alternate solutions to the problem.

asked Apr 8, 2019 at 19:31
$\endgroup$

1 Answer 1

3
$\begingroup$

If the helper function mutated the object c (which concat doesn't do in JS), then helper would have that side effect. But overall your intersection function wouldn't have any side effect that I can see, as the c array doesn't exist outside of it.

PS: concat returns a new array every time. The original c array is unchanged.

answered Apr 9, 2019 at 1:03
$\endgroup$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.