Rename ..Shapes..Data..vector to ..Shapes..Data..array
[shapes.git] / examples / doc / lexiographicSort.blank
blob8e0ef74481423173da56b18fca2467c3f39a7d4a
1 /** This file is part of Shapes.
2  **
3  ** Shapes is free software: you can redistribute it and/or modify
4  ** it under the terms of the GNU General Public License as published by
5  ** the Free Software Foundation, either version 3 of the License, or
6  ** any later version.
7  **
8  ** Shapes is distributed in the hope that it will be useful,
9  ** but WITHOUT ANY WARRANTY; without even the implied warranty of
10  ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  ** GNU General Public License for more details.
12  **
13  ** You should have received a copy of the GNU General Public License
14  ** along with Shapes.  If not, see <http://www.gnu.org/licenses/>.
15  **
16  ** Copyright 2014, 2015 Henrik Tidefelt
17  **/
19 ##needs ..Shapes..Data / seq-support
21 ##lookin ..Shapes
22 ##lookin ..Shapes..Data
24 /** Text input form of an array.
25  **/
26 vectorInputForm: \ v → (String..newString << `[array ´ << [seq_string [separate ` ´ v.list]] << ` ]´)
28 /** Data to be sorted.
29  **/
30 keys: [list
31         [array '~10 '~10]
32         [array '~10]
33         [array '5 '0 '0]
34         [array '~100]
35         [array '5 '0 '0]
36         [array ]
37         [array '~10 '5]
38         [array '5 '0]
39         [array '5 '10]
40       ]
42 /** Sort keys, and show.
43  **/
44 keysSorted: [lexiographicSort keys]
45 IO..•stdout << `Sorted keys:´ << "{n}
46 IO..•stdout << [seq_string [separate "{n} [fmap vectorInputForm keysSorted]]] << "{n}
48 /** Values to associate with keys.
49  ** Typically, the keys are computed based on the values, but this will be shown further down.
50  **/
51 values: [list `one´ `two´ `three´ `four´ `five´ `six´ `seven´ `eight´ `nine´]
53 /** Sort values associated with keys, and show.
54  **/
55 valuesSorted: [lexiographicSort keys values]
56 IO..•stdout << `Sorted values associated with keys:´ << "{n}
57 IO..•stdout << [seq_string [separate "{n} valuesSorted]] << "{n}
59 /** Now the typical situation where the keys are derived from the values.
60  ** Sort the string values in alphabetical order by deriving keys from the values.
61  ** Of course, a dedicated string sorting function would be mch more efficient, but
62  ** this example is just about showing how keys can naturally be derived from the
63  ** values to be sorted.
64  **/
65 stringKey: \ str → array [] <>[unlist [fmap ( \ i → [str.UTF8select i].code ) [range '0 count:str.UTF8count]]]
66 valueKeys: [fmap stringKey values]
67 IO..•stdout << `Keys derived from strings:´ << "{n}
68 IO..•stdout << [seq_string [separate "{n} [fmap vectorInputForm valueKeys]]] << "{n}
70 valuesAlphabetical: [lexiographicSort valueKeys values]
71 IO..•stdout << `Strings sorted alphabetically:´ << "{n}
72 IO..•stdout << [seq_string [separate "{n} valuesAlphabetical]] << "{n}