Following the advice I've read here and other sites, I've been trying to use the Mathematica equivalent of a linked lists...
testList = {{a, b}, {{c, d}, {{e, f}, {}}}}
Now, I want to see if {c,d}
is a member of testList
. How do I do that? MemeberQ doesn't transverse the list recursively and Flatten also nukes the sub lists. The following seems to work but I would expect there to be a cleaner simpler way...
memberInLinkedList[{}, _] = False;
memberInLinkedList[l_List, v_] := True /; First[l] == v;
memberInLinkedList[l_List, v_] := memberInLinkedList[Last[l], v];
Is there a more eloquent or built-in way to do this? Perhaps a general idiom or package that handles this transparently?
Answer
MemberQ[testList, {c, d}, Infinity]
True
Comments
Post a Comment