3
$\begingroup$

Is there a built-in function which will apply a function f to x when test yields true? A typical usage scenario would be the application of some transformation function depending on the options:

wrapif[Log, mydata, OptionValue["ReturnLogValues"]]

(*instead of*)

If[TrueQ@OptionValue["ReturnLogValues"], Log@mydata, mydata]

It is just a small piece of code to implement, but I need it quite often and wondered why I never found anything built-in. Example implementations:

wrapif[f_, x_, True] := f[x];
wrapif[f_, x_, _] := x;

Or:

wrapif2[f_, x_, test_] := Nest[f, x, Boole[TrueQ@condition]]
$\endgroup$
7
  • $\begingroup$ Another way would be to have "Filter" -> Indentity options and use it like OptionValue["Filter"] @ mydata. No you can easily pass Log there. $\endgroup$
    – Kuba
    Jun 21, 2018 at 12:10
  • $\begingroup$ What about myData // If[..., Log, Identity] $\endgroup$
    – Kuba
    Jun 21, 2018 at 12:55
  • $\begingroup$ wrapif3[f_, x_, test_] := Boole[test] f[x]+(1-Boole[test])x or wrapif4[f_, x_, test_] := {f, Identity}[[2 - Boole[test]]]@x? $\endgroup$
    – kglr
    Jun 21, 2018 at 13:00
  • $\begingroup$ ... wrapif5[f_, x_, test_] := First[RotateRight[{ Identity, f}, Boole[test]]]@x? $\endgroup$
    – kglr
    Jun 21, 2018 at 13:07
  • $\begingroup$ maybe this is not-quite-but-close: GeneralUtilities`MapIf[f_ test_]? $\endgroup$
    – kglr
    Jun 21, 2018 at 13:27

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.