5
$\begingroup$

I am trying to program the function MemberQ using less then possible functions pre defined by Mathematica. Until this now my code is:

meuMemberQ[f_,n_?NumericQ] /; (Length[Select[f, # == n &]] != 0):=True
meuMemberQ[f_,n_Symbol] /; (Length[Select[f, # == n &]] != 0) := True
meuMemberQ[f_,n_String] /; (Length[Select[f, # == n &]] != 0) := True
meuMemberQ[f_, n_] := False

There is a way to writing the same function but without using Select and Length?

Ps: It is just for exercise.

$\endgroup$
3
  • $\begingroup$ meuMemberQ2[f_, n_] := Intersection[f, {n}] === {n} or meuMemberQ3[f_,n_]:= SubsetQ[f, {n}]? $\endgroup$
    – kglr
    Commented Sep 4, 2018 at 23:02
  • $\begingroup$ So... the ideia is not use others functions. In this case, not using Intersection $\endgroup$
    – Mateus
    Commented Sep 4, 2018 at 23:04
  • $\begingroup$ Hint: loop through the list elements and test each with MatchQ. You could use AnyTrue for convenience, or simply Table for a very basic implementation. $\endgroup$
    – Szabolcs
    Commented Sep 5, 2018 at 8:12

3 Answers 3

6
$\begingroup$

A recursive implementation:

meuMemberQ[{n_, y___}, n_] := True;
meuMemberQ[{x_, y___}, n_] := meuMemberQ[{y}, n];
meuMemberQ[{}, n_] := False;

This just cuts through the list step by step looking for an exact match of n_, and if it gets to an empty list it returns False.

It will run into the iteration limit eventually, but if you need to use it with such long lists, there are things that can be done (such as using MemberQ).

$\endgroup$
6
$\begingroup$

A few alternatives:

ClearAll[meuMemberQ2, meuMemberQ3, meuMemberQ4]

meuMemberQ2[f_, n_] := Switch[n, Alternatives @@ f, True, _, False]
meuMemberQ3[f_, n_] := n /. {Alternatives@@f ->True, _:> False}

meuMemberQ4[{OrderlessPatternSequence[n_,___]}, n_] := True
meuMemberQ4[_,_]:=False
$\endgroup$
2
$\begingroup$

Using FirstCase

meuMemberQ[a_, b_] := 
 FirstCase[a, b] /. {_Missing :> False, _ :> True}

meuMemberQ[{1, 2, 3}, 2]

True

meuMemberQ[{"a", "b", "c"}, "d"]

False

meuMemberQ[{{1, 2}, {3, 4}}, {3, 4}]

True

$\endgroup$

Your Answer

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

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