2019年3月30日土曜日

An example of anonymous procedure (lambda expression) in NetLogo (2)

In the last article, I took an example using NetLogo's anonymous procedure (Lambda expressions). This time, as a continuation, I show another simple example. The problem is to find out pairs of right parenthesis and left parenthesis in multiple parentheses structures, as shown in Fig.1. The parentheses structure is given in a text format to the variable paren as shown in (a). The actual structure is as shown in (b). The result of detection of the pairs of left and right parenthesis is illustrated in (c).


This problem can be easily solved using a stack, as is well known. Here, referring to the documents [1] and [2], as shown in Fig. 2, the stack is represented by a list, and the operations of push and pop for it are given by lambda expressions (line 4-line 5). In pop, use the procedure getLast to get (and then to remove) the top element from the list. So far, it is still in preparation.

The actual parentheses check is performed by the foreach in line 5. First, please pay attention to "runresult paren". The variable paren is given the text as described above, but this input form has the ability to create this into a lambda expression for converting text to list. Therefore, runresult is applied. As a result, this part becomes a list. Foreach works on each element of this list, that is, on "(" or on ")". The variable "n" in the lambda expression in line 5 corresponds to one element of the list.

In the procedure "tinit", if the list element is "(", the value obtained by counting up the variable lpc is given to it as a label, and that element is pushed to the stack. On the other hand, if the list element is ")", get the label attached to the "(" at the top of the stack, and then set that label to the ")". This process determines the pair of parentheses. Since push is a lambda expression that does not return a value, it is evaluated by run, whereras,  pop is a lambda expression that returns a value, so it is evaluated by runresult.


Well, "(" and ")" are both turtle agents. In order to display it in an easy-to-understand manner, the shape was defined independently. NetLogo provides a shape editor that allows users to freely define necessary shapes as shown in Fig.3.


References
[1] Alan G. Isaac, https://subversion.american.edu/aisaac/notes/netlogo-intro.xhtml#tasks-vs-procedures
[2] NetLogo Dictionary, https://ccl.northwestern.edu/netlogo/docs/

0 件のコメント:

コメントを投稿