“Re-writing” the function `MemberQ`

“Re-writing” the function `MemberQ`



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


MemberQ


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?


Select


Length



Ps: It is just for exercise.





meuMemberQ2[f_, n_] := Intersection[f, n] === n or meuMemberQ3[f_,n_]:= SubsetQ[f, n]?
– kglr
Sep 4 '18 at 23:02



meuMemberQ2[f_, n_] := Intersection[f, n] === n


meuMemberQ3[f_,n_]:= SubsetQ[f, n]





So... the ideia is not use others functions. In this case, not using Intersection
– Mateus
Sep 4 '18 at 23:04


Intersection





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.
– Szabolcs
Sep 5 '18 at 8:12


MatchQ


AnyTrue


Table




2 Answers
2



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.


n_


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).


MemberQ



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



Thanks for contributing an answer to Mathematica Stack Exchange!



But avoid



Use MathJax to format equations. MathJax reference.



To learn more, see our tips on writing great answers.



Some of your past answers have not been well-received, and you're in danger of being blocked from answering.



Please pay close attention to the following guidance:



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế