2
$\begingroup$
ClearAll[fun]
Options[fun] = {key -> "k", val -> ""};
fun[OptionsPattern[]] := {OptionValue[key]-> OptionValue[val]}

fun[key -> "k", val -> "v"]
(* {"k" -> "v"} *)

fun[val -> #] & /@ {1, 2, 3}
(* {{"k" -> 1}, {"k" -> 2}, {"k" -> 3}} *)

MapThread[fun[key -> #1, val -> #2] &, {{"x", "y", "z"}, {1, 2, 3}}]
(* {{"x" -> 1}, {"y" -> 2}, {"z" -> 3}} *)

How is it possible to make fun Listable and get the same results

It seems I am missing something basic here, and I cannot find a relevant answer.

$\endgroup$
  • $\begingroup$ Are you asking for, e.g., fun[key -> {"x", "y", "z"}, val -> {1, 2, 3}] to return the same thing as your last output and whether this could be achieved with the attribute Listable on fun? $\endgroup$ – user31159 Mar 18 '16 at 17:36
  • $\begingroup$ @Xavier yes indeed, I want to set the Listable attribute on fun and return the same result. $\endgroup$ – Athanassios Mar 18 '16 at 17:49
  • $\begingroup$ @ShutaoTANG surprisingly this does not work directly for functions with rules as optional arguments ! You have to do the transformation of Xavier first. $\endgroup$ – Athanassios Mar 19 '16 at 7:33
3
$\begingroup$
ClearAll[fun]
Attributes[fun] = Listable;
Options[fun] = {key -> "k", val -> ""};

fun[OptionsPattern[]] := fun[OptionValue[key], OptionValue[val]];
fun[k_, v_] := {k -> v};

fun[key -> "k", val -> "v"]
(* {"k" -> "v"} *)

fun[val -> {1, 2, 3}]
(* {{"k" -> 1}, {"k" -> 2}, {"k" -> 3}} *)

fun[key -> {"x", "y", "z"}, val -> {1, 2, 3}]
(* {{"x" -> 1}, {"y" -> 2}, {"z" -> 3}} *)
$\endgroup$
  • $\begingroup$ thank you, this is a nice trick. If I understand well you transform the function with the optional arguments to a function with normal arguments. So I assume that if you do have some large body of this function to work out, you do all the processing in the body of fun[k_, v_], correct ? $\endgroup$ – Athanassios Mar 18 '16 at 18:34
  • $\begingroup$ @Athanassios Per transformation - Yes, exactly, and these normal arguments correspond to the values of the options. Per processing - Yes, and the processing should be done knowing that each of the arguments k and v in fun[k_, v_] correspond to one value only. $\endgroup$ – user31159 Mar 18 '16 at 18:48

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.