TransWikia.com

Can you unpack a list of values into variables in a With expression?

Mathematica Asked by ericmarkmartin on February 17, 2021

For instance, if I am trying to draw a graph with 5 vertices labeled a through e, and I want to draw edges connecting a and b, a and c, a and d, a and e, b and c, b and d, and c and e, I would run the following code.

{a, b, c, d, e} = CirclePoints[5]
Graphics[{
  {PointSize@Medium, Point[{a, b, c, d, e}]},
  Line[{
    {a, b}, {a, c}, {a, d}, {a, e},
    {b, c}, {b, d},
    {c, e}}]
}]

Which results in this graphic graph
(source: gdurl.com)

However, this becomes frustrating as a, b, c, d, and e are not bound to the Graphics call. Ideally, I’d like to be able to do something like:

With[{
    {a, b, c, d, e} = CirclePoints[5]
}, Graphics[{
      {PointSize@Medium, Point[{a, b, c, d, e}]},
      Line[{
        {a, b}, {a, c}, {a, d}, {a, e},
        {b, c}, {b, d},
        {c, e}}]
   }]
]

However, this results in an error

"Local variable specification {{a,b,c,d,e}=CirclePoints[5]} contains {a,b,c,d,e}=CirclePoints[5], which is an assignment to {a,b,c,d,e}; only assignments to symbols are allowed."

which makes sense, given that With does not have the desired capability, and neither do Block and Module.

So, is there a way to do this?

2 Answers

The answer is no. The 1st argument of With does not allow destructuring. It only accepts a list of simple assignments.

I would rewrite the example you give as

Module[{a, b, c, d, e},
  {a, b, c, d, e} = CirclePoints[5]; 
  Graphics[
    {{PointSize @ Medium, Point[{a, b, c, d, e}]}, 
     Line[{{a, b}, {a, c}, {a, d}, {a, e}, {b, c}, {b, d}, {c, e}}]}]]

Correct answer by m_goldberg on February 17, 2021

You could do this:

Function[{a, b, c, d, e}, 
 Graphics[{{PointSize@Medium, Point[{a, b, c, d, e}]}, 
 Line[{{a,b}, {a,c}, {a,d}, {a,e}, {b,c}, {b,d}, {c, e}}]}]]@@CirclePoints[5] 

I used a Function to localize the variables and then applied it to the desired points with @@.

Answered by Jens on February 17, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP