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?

  • 1
    $\begingroup$ 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. $\endgroup$ – m_goldberg Jan 21 '19 at 17:53
  • $\begingroup$ 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. $\endgroup$ – Kuba Jan 21 '19 at 18:36

That is straightforward:

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:

Options[recKeyFreeQ] = {SameTest -> SameQ};
recKeyFreeQ[assoc : <|fst_, ___|>, el_, opt : OptionsPattern[]] := 
 If[OptionValue[SameTest][First@fst, el], 
  recKeyFreeQ[Rest@assoc, el, opt]] 
recKeyFreeQ[<||>, el_, OptionsPattern[]] := True
  • $\begingroup$ In this way is easy because you used the function Keys. Is there a way to do the same without using? $\endgroup$ – Mateus Jan 21 '19 at 18:14
  • $\begingroup$ KeyFreeQ[<|{1} -> 2|>, 1] =!= FreeQ[Keys@<|{1} -> 2|>, 1]. $\endgroup$ – Kuba Jan 21 '19 at 18:38
  • 1
    $\begingroup$ @Kuba that's a fair point. I added a level spec to FreeQ which corrects it. $\endgroup$ – rcollyer Jan 21 '19 at 19:43
  • 1
    $\begingroup$ @Mateus I added a recursive form similar to meuFreeQ. $\endgroup$ – rcollyer Jan 21 '19 at 20:17
  • 1
    $\begingroup$ KeyFreeQ and Keys also work on lists of rules (in addition to Associations). (+1) $\endgroup$ – kglr Jan 21 '19 at 20:31

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.