# Creating my own function that mimics KeyFreeQ

I want to create my own function KeyFreeQ using Mathematica's functions as little as possible.

For example: I already have my own function FreeQ:

meuFreeQ // ClearAll
meuFreeQ[{n_, y___}, n_] := False;
meuFreeQ[{x_, y___}, n_] := meuFreeQ[{y}, n];
meuFreeQ[{}, n_] := True;


How can I do the same for KeyFreeQ?

• Some pointers: There is no reason to use CiearAll when you do not give a function attributes. There is no reason to use SetDelayed when the righthand side is a constant. – m_goldberg Jan 21 '19 at 17:53
• Your version does not work correctly: FreeQ[{{1}}, 1] =!= meuFreeQ[{{1}}, 1]. Is this your code? Because I am not sure why are you stuck at KeyFreeQ if you already did this. – Kuba Jan 21 '19 at 18:36

## 1 Answer

That is straightforward:

Clear[mKeyFreeQ];
mKeyFreeQ[a_?AssociationQ, k_] := FreeQ[Keys[a], k, 1]


You could, in principle, replace the instance of FreeQ with meuFreeQ, too.

Per request, this can be written in the same type of recursive pattern the OPs meuFreeQ is written in:

Clear[recKeyFreeQ];
Options[recKeyFreeQ] = {SameTest -> SameQ};
recKeyFreeQ[assoc : <|fst_, ___|>, el_, opt : OptionsPattern[]] :=
If[OptionValue[SameTest][First@fst, el],
False,
recKeyFreeQ[Rest@assoc, el, opt]]
recKeyFreeQ[<||>, el_, OptionsPattern[]] := True

• In this way is easy because you used the function Keys. Is there a way to do the same without using? – Mateus Jan 21 '19 at 18:14
• KeyFreeQ[<|{1} -> 2|>, 1] =!= FreeQ[Keys@<|{1} -> 2|>, 1]. – Kuba Jan 21 '19 at 18:38
• @Kuba that's a fair point. I added a level spec to FreeQ which corrects it. – rcollyer Jan 21 '19 at 19:43
• @Mateus I added a recursive form similar to meuFreeQ. – rcollyer Jan 21 '19 at 20:17
• KeyFreeQ and Keys also work on lists of rules (in addition to Associations). (+1) – kglr Jan 21 '19 at 20:31