With SageMath, one can do FiniteSetMaps(["a", "b"], [3, 4, 5])
to get all maps from {a,b}
to {3,4,5}
. Is something similar available in Mathematica?
2 Answers
alist = {3, 4, 5};
blist = {"a", "b"};
mapfs = Tuples@Outer[Rule, blist, alist]
$$\begin{array}{l} \{\text{a}\to 3,\text{b}\to 3\} \\ \{\text{a}\to 3,\text{b}\to 4\} \\ \{\text{a}\to 3,\text{b}\to 5\} \\ \{\text{a}\to 4,\text{b}\to 3\} \\ \{\text{a}\to 4,\text{b}\to 4\} \\ \{\text{a}\to 4,\text{b}\to 5\} \\ \{\text{a}\to 5,\text{b}\to 3\} \\ \{\text{a}\to 5,\text{b}\to 4\} \\ \{\text{a}\to 5,\text{b}\to 5\} \\ \end{array}$$
EDIT
Following comment by @Alan (Thanks)
mapasc = Map[Association, mapfs]
mapasc[[2]]["b"]
4
-
$\begingroup$ How can the elements in
mapfs
be made executable, for examplemapfs[[2]]["b"]
should return4
? $\endgroup$– ThrashCommented May 15, 2022 at 17:22 -
-
$\begingroup$ For that, I have to know in which position
b
is. How can a function in mapfs be made executable by its respective argument like "a" or "b"? $\endgroup$– ThrashCommented May 15, 2022 at 17:35 -
1
-
3$\begingroup$ @Thrash Just map
Association
overmapfs
. $\endgroup$– AlanCommented May 15, 2022 at 19:25
There's no built-in function but the following constructs the mappings:
aa = {"a", "b"};
bb = {3, 4, 5};
Thread[aa -> #] & /@ Tuples[bb, Length@aa]
If you want "functional" expressions, then one way to get them is
funcs = ReplaceAll@Thread[aa -> #] & /@ Tuples[bb, Length@aa]
funcs[[2]]["b"]
(* 4 *)
-
$\begingroup$ Thank you! I tried it first in a more direct way via
f/@aa = {3,4}
for example, but I getSet::write: Tag Map in f /@ {a, b} is Protected.
. Why can't be several values assigned at once? $\endgroup$– ThrashCommented May 15, 2022 at 17:19 -
1$\begingroup$ @Thrash Try
Evaluate[f /@ aa] = {3, 4}
. $\endgroup$ Commented May 15, 2022 at 17:20
Function
or ordered pairs orRule
? $\endgroup$