OSDN Git Service

【更新内容】
[ring-lang-081/ring.git] / docs / en / target / lists.txt
1 .. index:: 
2         single: Lists; Introduction
3
4 =====
5 Lists
6 =====
7
8 In this chapter we are going to learn how to deal with lists.
9
10 .. index:: 
11         pair: Lists; Create Lists
12
13 Create Lists
14 ============
15
16 We can create new lists by defining the list items inside square bracts.
17
18 Example:
19
20 .. code-block:: ring
21
22         aList = [1,2,3,4,5]
23
24 Also we can create new lists using the : operator
25
26
27 Example:
28
29 .. code-block:: ring
30
31         aList = 1:5
32         aList2 = "a":"z"
33
34 Example:
35
36 .. code-block:: ring
37
38         aList = 5:1
39         aList2 = "z":"a"
40
41 Also we can create lists using the list() function
42
43 Syntax:
44
45 .. code-block:: ring
46
47         list = list(size)
48
49 Example
50
51 .. code-block:: ring
52
53         aList = list(10)        # aList contains 10 items
54
55 .. note:: the list index start from 1 
56
57 .. index:: 
58         pair: Lists; Add Items
59
60 Add Items
61 =========
62
63 To add new items to the list, we can use the Add() function.
64
65 Syntax:
66
67 .. code-block:: ring
68
69         Add(List,Item)
70
71
72 Example:
73
74 .. code-block:: ring
75
76         aList = ["one","two"]
77         add(aList,"three")
78         see aList
79
80 Also we can do that using the + operator.
81
82 Syntax:
83
84 .. code-block:: ring
85
86         List + item
87
88 Example:
89
90 .. code-block:: ring
91
92         aList = 1:10    # create list contains numbers from 1 to 10
93         aList + 11      # add number 11 to the list
94         see aList       # print the list
95
96 .. index:: 
97         pair: Lists; Get List Size
98
99 Get List Size
100 =============
101
102 We can get the list size using the len() function
103
104 Syntax:
105
106 .. code-block:: ring
107
108         Len(List)
109
110 Example:
111
112 .. code-block:: ring
113
114         aList = 1:20  see len(aList)  # print 20
115
116 .. index:: 
117         pair: Lists; Delete Item From List
118
119 Delete Item From List
120 =====================
121
122 To delete an item from the list, we can use the del() function
123
124 Syntax:
125
126 .. code-block:: ring
127
128         del(list,index)
129
130 Example:
131
132 .. code-block:: ring
133
134         aList = ["one","two","other","three"]
135         Del(aList,3)    # delete item number three
136         see aList       # print one two three
137
138
139 .. index:: 
140         pair: Lists; Get List Item
141         
142 Get List Item
143 =============
144
145 To get an item from the list, we uses the next syntax
146
147 .. code-block:: ring
148
149         List[Index]
150
151 Example:
152
153 .. code-block:: ring
154
155         aList = ["Cairo","Riyadh"]
156         see "Egypt : " + aList[1] + nl +
157             "KSA   : " + aList[2] + nl
158
159 .. index:: 
160         pair: Lists; Set List Item
161
162 Set List Item
163 =============
164
165 To set the value of an item inside the list, we can use the next syntax
166
167 .. code-block:: ring
168
169         List[Index] = Expression
170
171 Example:
172
173 .. code-block:: ring
174
175         aList = list(3) # create list contains three items
176         aList[1] = "one" aList[2] = "two" aList[3] = "three"
177         see aList
178
179 .. index:: 
180         pair: Lists; Search
181
182 Search
183 ======
184
185 To find an item inside the list we can use the find() function
186
187 Syntax:
188
189 .. code-block:: ring
190
191         Find(List,ItemValue) ---> Item Index
192         Find(List,ItemValue,nColumn) ---> Search in nColumn, returns the Item Index 
193         Find(List,ItemValue,nColumn,cAttribute) ---> Item Index
194
195 Example:
196
197 .. code-block:: ring
198
199         aList = ["one","two","three","four","five"]
200         see find(aList,"three")         # print 3
201
202 Example:
203
204 .. code-block:: ring
205
206         mylist = [["one",1],
207                   ["two",2],
208                   ["three",3]]
209
210         see find(mylist,"two",1) + nl           # print 2
211         see find(mylist,2,2) + nl               # print 2
212
213 Also we can use the binarysearch() function to search in sorted list.
214
215 Syntax:
216
217 .. code-block:: ring
218
219         BinarySearch(List,ItemValue) ---> Item Index
220         BinarySearch(List,ItemValue,nColumn) ---> Search in nColumn, returns the Item Index 
221
222 Example:
223
224 .. code-block:: ring
225
226         aList = ["one","two","three","four","five"]
227         aList = sort(aList)
228         see binarysearch(aList,"three")
229
230 Output:
231
232 .. code-block:: ring
233
234         five
235         four
236         one
237         three
238         two
239         4
240
241 .. index:: 
242         pair: Lists; Sort()
243
244 Sort
245 ====
246
247 We can sort the list using the sort() function.
248
249 Syntax:
250
251 .. code-block:: ring
252
253         Sort(List) ---> Sorted List
254         Sort(List,nColumn) ---> Sorted List based on nColumn 
255         Sort(List,nColumn,cAttribute) ---> Sorted List based on Object Attribute
256
257 Example:
258
259 .. code-block:: ring
260
261         aList = [10,12,3,5,31,15]
262         aList = sort(aList) see aList # print 3 5 10 12 15 31
263
264 We can sort list of strings
265
266 Example:
267
268 .. code-block:: ring
269
270         mylist = ["mahmoud","samir","ahmed","ibrahim","mohammed"]
271         see mylist                # print list before sorting
272         mylist = sort(mylist)     # sort list
273         see "list after sort"+nl
274         see mylist                # print ahmed ibrahim mahmoud mohammed samir
275
276 We can sort a list based on a specific column.
277
278 Example:
279
280 .. code-block:: ring
281
282         aList = [ ["mahmoud",15000] ,
283                   ["ahmed", 14000 ] ,
284                   ["samir", 16000 ] ,
285                   ["mohammed", 12000 ] ,
286                   ["ibrahim",11000 ] ]
287
288         aList2 = sort(aList,1)
289         see aList2
290
291 Output:
292
293 .. code-block:: ring
294
295         ahmed
296         14000
297         ibrahim
298         11000
299         mahmoud
300         15000
301         mohammed
302         12000
303         samir
304         16000
305
306
307 .. index:: 
308         pair: Lists; Reverse()
309
310 Reverse
311 =======
312
313 We can reverse a list using the reverse() function.
314
315 Syntax:
316
317 .. code-block:: ring
318
319         Reverse(List) ---> Reversed List
320
321 Example:
322
323 .. code-block:: ring
324
325         aList = [10,20,30,40,50]
326         aList = reverse(aList)
327         see aList       # print 50 40 30 20 10
328
329 .. index:: 
330         pair: Lists; Insert()
331
332 Insert Items
333 ============
334
335 To insert an item in the list we can use the insert() function.
336
337 Syntax:
338
339 .. code-block:: ring
340
341         Insert(List,Index,Item)
342
343 The inserted item will be AFTER the Index
344
345 Example:
346
347 .. code-block:: ring
348
349         aList = ["A","B","D","E"]
350         insert(aList,2,"C")    # Inserts AFTER Index 2, "C" into Position 3
351         see aList              # print A B C D E
352
353
354 .. index:: 
355         pair: Lists; Nested Lists
356
357 Nested Lists
358 ============
359
360 The list may contain other lists
361
362 Example:
363
364 .. code-block:: ring
365
366         aList = [ 1 , [10,20,30] , 5 , [100,1000,5000] ]
367         aList2 = [
368         "one","two", 
369         [3,4],
370         [20,30], ["three",
371                   "four",
372                   "five",[100,200,300]
373                  ]
374         ]
375         
376         see aList[2]            # print 10 20 30
377         see aList[4][3] + nl    # print 5000
378         see aList2[5][2] + nl   # print four
379         see aList2[5][4][3]     # print 300
380
381 .. index:: 
382         pair: Lists; Copy Lists
383
384 Copy Lists
385 ==========
386
387 We can copy lists (including nested lists) using the Assignment operator.
388
389 Example:
390
391 .. code-block:: ring
392
393         aList = [
394         "one","two", 
395         [3,4],
396         [20,30], ["three",
397                   "four",
398                   "five",[100,200,300]
399                  ]
400         ]
401
402         aList2 = aList          # Copy aList to aList2
403         aList2[5] = "other"     # modify item number five
404         see aList2[5] + nl      # print other
405         see aList[5]            # print three four five 100 200 300
406
407
408 .. index:: 
409         pair: Lists; First-Class Lists
410
411 First-class lists
412 =================
413
414 Lists are `first-class citizens <http://en.wikipedia.org/wiki/First-class_citizen>`_ where we can store
415 lists in variables, pass lists to functions, and return lists from functions.
416
417 Example:
418
419 .. code-block:: ring
420
421         aList = duplicate( [1,2,3,4,5] )
422         see aList[10] + nl                # print 5
423
424         see mylist()                      # print 10 20 30 40 50
425         
426         func duplicate list
427                 nMax = len(list)
428                 for x = 1 to nMax
429                         list + list[x]
430                 next
431                 return list
432
433         func mylist return [10,20,30,40,50]
434
435 .. index:: 
436         pair: Lists; Using Lists during definition
437                 
438 Using Lists during definition
439 =============================
440
441 We can use the list items while we are defining the list for the first time.
442
443 Example:
444
445 .. code-block:: ring
446
447         aList = [ [1,2,3,4,5] , aList[1] , aList[1] ]
448         see aList       # print 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5
449         
450         
451 .. index:: 
452         pair: Lists; Passing Lists to Functions
453
454 Passing Lists to Functions
455 ==========================
456
457 Lists are passed to functions by reference, This means that the called
458 function will work on the same list and can modify it.
459
460 Example:
461
462 .. code-block:: ring
463
464         func main
465                 aList = [1,2,3,4,5]     # create list, local in function main
466                 myfunc(aList)           # call function, pass list by reference
467                 see aList               # print 1 2 3 4 5 6 7 8 9 10
468
469         func myfunc list
470                 list + [6,7,8,9,10]
471
472
473 .. index:: 
474         pair: Lists; Access List Items by String Index
475
476 Access List Items by String Index
477 =================================
478
479 Instead of using numbers to determine the item index when we get item value or set item value,
480 We can access items using string index if the item is a list contains two items and 
481 the first item is a string.
482
483 Example:
484
485 .. code-block:: ring
486
487         aList = [ ["one",1] , ["two",2] , ["three",3] ]
488         see aList["one"] + nl +
489             aList["two"] + nl +
490             aList["three"]      # print 1 2 3
491
492 This type of lists can be defined in a better syntax using the : and = operators.
493
494 Example:
495
496 .. code-block:: ring
497
498         aList = [ :one = 1 , :two = 2 , :three = 3 ]
499         see aList["one"] + nl +
500             aList["two"] + nl +
501             aList["three"] + nl # print 1 2 3
502         see aList[1]            # print one 1
503
504 .. tip:: using : before identifier (one word) means literal
505
506 .. note:: using = inside list definition create a list of two items where
507           the first item is the left side and the second item is the right side.
508
509 We can add new items to the list using the string index
510
511 Example:
512
513 .. code-block:: ring
514         
515         aList = []
516         aList["Egypt"] = "Cairo"
517         aList["KSA"] = "Riyadh"
518         see aList["Egypt"] + nl +       # print Cairo
519             aList["KSA"] + nl           # print Riyadh
520
521 .. index:: 
522         pair: Lists; Passing Parameters or Arguments Using List
523
524 Passing Parameters or Argumnents Using List
525 ===========================================
526         
527 This type of lists is very good for passing parameters to functions
528 Where the order of parameters will not be important (we can change the order).
529
530 Also some parameters maybe optional.
531
532 Example:
533
534 .. code-block:: ring
535
536         myconnect (  [ :server = "myserver.com" , :port = 80 , 
537                        :username = "mahmoud" , :password = "password" ] ) 
538
539         func myconnect mypara
540         
541                 # print connection details
542                 see "User Name : " + mypara[:username] + nl +
543                     "Password  : " + mypara[:password] + nl +
544                     "Server    : " + mypara[:server] + nl +
545                     "Port      : " + mypara[:port]
546 .. index:: 
547         pair: Lists; Passing Parameters Arguments Using List Array
548
549 Passing Parameters or Argumnents Using List Array
550 =================================================
551         
552 Passing Arguments or Parmameters to a Function in an array format
553
554 Example:
555
556 .. code-block:: ring
557
558      myList = [5,7,3,9]    ### list with args or parms in  an array
559      result = sum(myList)
560      See "Sum result: "+ result +n
561
562      func sum(aList)
563        acc = 0
564        sizeList = len(aList)
565    
566        for i = 1 to sizeList
567           See aList[i] +nl
568           acc = acc + aList[i]
569        next
570      return acc
571  
572
573 .. index:: 
574         pair: Lists; Return as List or Hash Table
575
576 Return Parameters as List or Hash Table
577 =======================================
578         
579 Return Parameters from a Function in an Array or Hash Format
580
581 Example:
582
583 .. code-block:: ring
584
585         sudoku = [  [2,9,0],
586                     [0,0,1],
587                     [0,0,0] ]
588
589         aOutput = myFunctionArray(sudoku)
590                 See "Return Array: T/F: "+ aOutput[1] +" Row: "+ aOutput[2] +" Col: "+ aOutput[3] +nl
591
592         aOutput = myFunctionHash(sudoku)
593                 See "Return Hash.: T/F: "+ aOutput[:lValue] +" Row: "+ aOutput[:nRow] +" Col: "+ aOutput[:nCol] +nl
594
595         ###----------------------------------
596         ### isSolvedSoduku - Return ARRAY
597
598         Func myFunctionArray(sudoku)
599             for Row = 1 to 9
600                 for Col = 1 to 9
601                     if sudoku[Row][Col] = 0
602
603                         //----------------------------
604                         // Return Array with 3 fields       
605                         return [False, Row, Col]                    
606                     ok
607                 next
608             next
609         return [True, Row, Col]
610
611         ###----------------------------------
612         ### isSolvedSoduku - Return HASH
613
614         Func myFunctionHash(sudoku)
615             for Row = 1 to 3
616                 for Col = 1 to 3
617                     if sudoku[Row][Col] = 0
618
619                         //---------------------------------
620                         // Return Hash Table with 3 fields      
621                         return  [   :lValue = False, 
622                                     :nRow   = Row, 
623                                     :nCol   = Col   
624                                 ]
625                     ok
626                 next
627             next
628
629         return  [ :lValue = False, :nRow = Row, :nCol = Col ]           
630
631         ###-----------------------------
632
633      
634 .. index:: 
635         pair: Lists; Create Multi Dimension Array  Using List and Recursion
636
637 Creating a Multi-Dimensional Array using  List
638 ==============================================
639         
640 A Multi-Dimensional Array of any size can be built using recursion in a  Function
641
642 Example:
643
644 .. code-block:: ring
645
646         ###---------------------------------------------------------
647         ### Create Array -- Dimensions Any Size:  3D, 4D, 5D etc
648
649         dimList = [4,3,4]
650         bList   = createDimList(dimList)
651         
652         ###---------------------------------------------------------
653         ### Populate the arrays using a counter 1 ,  4x4x4 = 256 , 2x3x4x5x6 = 720
654
655         Counter = 1
656
657         for Col=1 to dimList[1]
658           for Row=1 to dimList[2]
659             for Dep=1 to dimList[3]
660                     blist[Col][Row][Dep] = Counter
661                     Counter++
662             next
663           next
664         next
665
666         ###-----------------------------------------------
667         ### Print the array elements in block format
668
669         for Col=1 to dimList[1]
670           for Row=1 to dimList[2]
671             for Dep=1 to dimList[3]
672                     See bList[Col][Row][Dep] See " "
673             next
674             See nl
675           next
676             See nl
677         next
678
679         ###===========================
680         ### FUNCTIONS
681
682         ###-----------------------------------------------------------------------
683         ### Recursive Create a Dimension Array
684         ### Call by passing an array of dimesions: dimList = [2,3,4,5]
685         ### Drop the first entry every iteration call, making newParms
686         ###
687         ### Example:
688         ###    dimList = [4,2,3,2]                <<< Number and size of dimensions in array format
689         ###    bList   = createDimList(dimList)   <<< Call using the array as input
690
691         func createDimList(dimArray)
692
693              sizeList = len(dimArray)
694
695              newParms = []
696              for i = 2 to sizeList
697                 Add(newParms, dimArray[i])
698              next
699
700              alist = list(dimArray[1])
701
702              if sizeList = 1
703                 return aList
704              ok
705
706              for t in alist
707                  t = createDimList(newParms)
708              next
709
710         return alist
711         
712      
713 .. index:: 
714         pair: Lists; Swap Items
715
716 Swap Items
717 ==========
718
719 We can swap the list items using the Swap() function.
720
721 Example:
722
723 .. code-block:: ring
724
725         aList = [:one,:two,:four,:three]
726         see aList
727         see copy("*",50) + nl
728         swap(aList,3,4)
729         see aList
730
731 Output
732
733 .. code-block:: ring
734
735         one
736         two
737         four
738         three
739         **************************************************
740         one
741         two
742         three
743         four
744
745