2
$\begingroup$

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?

$\endgroup$
2
  • 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
    Commented Jan 21, 2019 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
    Commented Jan 21, 2019 at 18:36

1 Answer 1

3
$\begingroup$

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

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.