local variables for repeated occurrences of subexpressions

Niek Sprakel shared this question 11 months ago
Answered

Hi.

Is there any way in GeoGebra to work with local variables to compactify expressions?

Things get really unwieldy if you have a large subexpression that occurs multiple times within a larger expression.

For instance, in the following expression, it's cumbersome to repeat certain subexpressions like "(0,f(p)Element(Element(m1,p),3))" multiple times, so it would be nice if you could have something like a local variable to substitute for that repeated subexpression to take care of that:

Sequence({Segment(Element(Element(m1,p),1),Element(Element(m1,p),1)+ (0,f(p)Element(Element(m1,p),3))),Segment(Element(Element(m1,p),2),Element(Element(m1,p),2)+ (0,f(p)Element(Element(m1,p),3))),Semicircle(Element(Element(m1,p),1)+ (0,f(p)Element(Element(m1,p),3)),Element(Element(m1,p),2)+ (0,f(p)Element(Element(m1,p),3)))},p,1,v)


The attached ggb file is an experiment to visualize gaps between prime numbers where I ran into this issue.

greetings and thanks in advance for any suggestions, Niek

Comments (4)

photo
1

This doesn't directly answer your question about local variables, but one thing you can do to shorten your code is to avoid using the Element() command. A better way to access list elements is to use the list name directly. Say you have L = { {1,2}, {3,4}, {5,6}, {7,8} }. Then you can call L(3) to get {5,6}, and if you call L(3,1), you get 5.

So, in your code, you have Element(Element(m1,p),1), but this could be shortened to m1(p,1).

photo
1

Ah, thanks. I also noticed this more compact way to refer to elements of a list in the wiki pages of GeoGebra and it does reduce the expressions quite a bit. Though it seems that sometimes it interprets a list of lists as a matrix, if the elements have the same length. I guess using a list of tuples would also be an option, where x(t), y(t) and z(t) can be used to refer to the components of a tuple t.

photo
photo
1

I do not know if there is a way; I use the replacement feature of word or another editor

photo
1

You can abuse the Zip function to effectively create local computed constants from single-item lists, then use Join to remove the outer layer of nesting created by the Zip:

Join[Zip[expression-of-a-and-b, a, {formula-for-a}, b, {formula-for-b}]]


Note that the an index variable named “i” which works in the Sequence command does not work in a Zip command (except for an enclosing Sequence construct). Use something like “ix” instead.

© 2020 International GeoGebra Institute