i'm struggling to implement the following parametric function:

I need to create a g function with two arguments (w and v). If w and v are not empty lists, then it will return a list containing two other lists: - one containing the elements of w that do not occur in v, - and the other containing the elements of v that do not occur in w, If one of w or v are empty lists, it should return a message "One of the lists is empty".

Hope anyone can help me out here, thanks in advance.

  • $\begingroup$ Seems quite straightforward. Check the docs for If[] and Complement[] $\endgroup$ – Dr. belisarius Jan 9 '15 at 17:37
  • $\begingroup$ Try g[w_, v_] := If[w == {} || v == {}, "D'oh!", {Complement[w, v], Complement[v, w]}]. $\endgroup$ – DumpsterDoofus Jan 9 '15 at 17:43
  • $\begingroup$ I added my comment as an answer. If people think this question is trivial enough to be closed, I'll delete my answer and vote to close for "easily found in the documentation" and leave my answer as the comment above. $\endgroup$ – DumpsterDoofus Jan 9 '15 at 18:00
  • $\begingroup$ Regardless, the title is unrelated to the question (which has nothing to do with parametric functions). If this question is to remain, the title should be changed to reflect the actual question. $\endgroup$ – David G. Stork Jan 9 '15 at 20:16
  • $\begingroup$ Thanks, i'm starting to learn the mathematica basics and i've been doing exercises ok so far. From recursive, imperative and functional functions to parametric(that's how they call it in my class). I'm a bit stuck here, and the info i look online isn't very clear. Nonetheless your help was quite valuable for me, i must keep searching and trying to learn this. $\endgroup$ – Luis Jan 9 '15 at 20:54

Try the following:

g[w_, v_] := If[w == {} || v == {}, "D'oh!", {Complement[w, v], Complement[v, w]}]

Some tests:

g[{2, 3, 4}, {2, 5}]
g[{2}, {}]


{{3, 4}, {5}}

Here is an alternative, using dispatch between multiple definitions:

g[{},_] = g[_,{}] = "One of the lists is empty";
g[a_,b_] := { a~Complement~b, b~Complement~a };

If you like syntactic sugar, you could also write the second line as

g[a_,b_] := Complement @@@ { {a,b}, {b,a} };

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.