Skip to content

Commit 02fd959

Browse files
committed
Add new functions documentation
1 parent 779f4f9 commit 02fd959

File tree

3 files changed

+185
-60
lines changed

3 files changed

+185
-60
lines changed

docs/src/modules/functional.yml

Lines changed: 127 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,11 @@ constants:
1010
desc: "function which returns passed argument"
1111
desc_ru: "функция, которая возвращает переданный в неё аргумент"
1212
functions:
13-
- name: "chain"
13+
- name: chain
1414
args: "data, functions..."
1515
desc: ""
1616
desc_ru: ""
17-
- name: "combine"
17+
- name: combine
1818
args: "functions..."
1919
desc: "combines functions"
2020
desc_ru: "комбинирует функции (композиция)"
@@ -55,7 +55,7 @@ functions:
5555
5656
nums = [1,2,3,4,5]
5757
print filter(nums, def(x) = x % 2 == 0) // [2, 4]
58-
- name: "flatmap"
58+
- name: flatmap
5959
args: "array, mapper"
6060
desc: "converts each element of an array to other array"
6161
desc_ru: "преобразует каждый элемент массива в массив элементов"
@@ -69,7 +69,7 @@ functions:
6969
arr[i] = x
7070
return arr
7171
}) // [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
72-
- name: "foreach"
72+
- name: foreach
7373
args: "data, consumer"
7474
desc: "invokes function `consumer` for each element of array or map `data`\n\nIf `data` - массив, то в функции consumer необходим один параметр, если объект - два (ключ и значение)."
7575
desc_ru: "для каждого элемента в массиве или объекте `data` вызывает функцию `consumer`\n\nЕсли `data` - массив, то в функции `consumer` необходим один параметр, если объект - два (ключ и значение)."
@@ -80,7 +80,7 @@ functions:
8080
foreach({"key": 1, "key2": "text"}, def(key, value) {
8181
print key + ": " + value
8282
})
83-
- name: "map"
83+
- name: map
8484
args: "data, mapper..."
8585
desc: "converts elements of array or map. If `data` is array - `mapper` converts his elements, if `data` is object - you need to pass `keyMapper` - converts keys and `valueMapper` - converts values"
8686
desc_ru: "преобразует элементы массива или объекта.\n\nЕсли `data` - массив, то функция `mapper` преобразует значения, если объект - необходимо передать две функции: `keyMapper` - преобразует ключи и `valueMapper` - преобразует значения"
@@ -89,7 +89,7 @@ functions:
8989
9090
nums = [3,4,5]
9191
print map(nums, def(x) = x * x) // [9, 16, 25]
92-
- name: "reduce"
92+
- name: reduce
9393
args: "data, identity, accumulator"
9494
desc: "converts elements of an array or a map to one value, e.g. sum of elements or concatenation string. `accumulator` takes one argument for array and two arguments for object (key and value)."
9595
desc_ru: "преобразует элементы массива или объекта в одно значение, например сумма элементов или объединение в строку.\n\nЕсли `data` - массив, то в функции `accumulator` необходим один параметр, если объект - два (ключ и значение)"
@@ -98,10 +98,10 @@ functions:
9898
9999
nums = [1,2,3,4,5]
100100
print reduce(nums, 0, def(x, y) = x + y) // 15
101-
- name: "sortby"
101+
- name: sortby
102102
args: "array, function"
103-
desc: "sorts elements of an array or an object by `function` result"
104-
desc_ru: "сортирует элементы массива по данным в функции `function`"
103+
desc: "sorts elements of an array or a map by `function` result"
104+
desc_ru: "сортирует элементы массива или объекта по данным в функции `function`"
105105
example: |-
106106
use functional
107107
@@ -111,51 +111,125 @@ functions:
111111
{"k1": 4, "k2": "z"},
112112
{"k1": 5, "k2": "p"},
113113
]
114-
print sortby(data, def(v) = v.k1) // [{k1=2, k2=x}, {k1=4, k2=z}, {k1=5, k2=p}, {k1=7, k2=d}]
115-
print sortby(data, def(v) = v.k2) // [{k1=7, k2=d}, {k1=5, k2=p}, {k1=2, k2=x}, {k1=4, k2=z}]
116-
- name: "stream"
117-
args: "data"
118-
desc: |-
119-
creates stream from data and returns StreamValue
120-
121-
StreamValue functions:
122-
- `filter(func)` - filters elements
123-
- `map(func)` - converts each element
124-
- `flatMap(func)` - converts each element to array
125-
- `sorted(func)` - sorts elements with comparator function
126-
- `sortBy(func)` - applies function, then sorts elements
127-
- `takeWhile(func)` - takes elements while predicate function returns true
128-
- `dropWhile(func)` - skips elements while predicate function returns true
129-
- `peek(func)` - executes function for each element and returns stream
130-
- `skip(count)` - skips count elements
131-
- `limit(count)` - limits elements size
132-
- `custom(func)` - performs custom operation
133-
- `reduce(func)` - converts elements to one value
134-
- `forEach(func)` - executes function for each element
135-
- `joining(delimiter = "", prefix = "", suffix = "")` - joins elements into a string
136-
- `toArray()` - returns array of elements
137-
- `count()` - returns count of elements
138-
desc_ru: |-
139-
создаёт stream из данных и возвращает StreamValue
114+
println sortby(data, def(v) = v.k1) // [{k1=2, k2=x}, {k1=4, k2=z}, {k1=5, k2=p}, {k1=7, k2=d}]
115+
println sortby(data, def(v) = v.k2) // [{k1=7, k2=d}, {k1=5, k2=p}, {k1=2, k2=x}, {k1=4, k2=z}]
116+
- name: groupby
117+
args: "data, function"
118+
desc: "groups elements of an array or a map by `function` result"
119+
desc_ru: "группирует элементы массива или объекта на основе результата функции `function`"
120+
since: 2.0.0
121+
example: |-
122+
use functional
140123
141-
Функции StreamValue:
142-
- `filter(func)` - фильтрует элементы
143-
- `map(func)` - преобразует каждый элемент
144-
- `flatMap(func)` - преобразует каждый элемент в массив
145-
- `sorted(func)` - сортирует элементы в соответствии с функцией-компаратором
146-
- `sortBy(func)` - применяет функцию, затем сортирует элементы
147-
- `takeWhile(func)` - собирает элементы пока функция-предикат возвращает true
148-
- `dropWhile(func)` - пропускает элементы пока функция-предикат возвращает true
149-
- `peek(func)` - вызывает функцию для каждого элемента и возвращает stream
150-
- `skip(count)` - пропускает указанное количество элементов
151-
- `limit(count)` - ограничивает количество элементов
152-
- `custom(func)` - выполняет пользовательскую операцию над данными
153-
- `reduce(func)` - преобразует элементы в одно значение
154-
- `forEach(func)` - вызывает функцию для каждого элемента
155-
- `joining(delimiter = "", prefix = "", suffix = "")` - склеивает элементы в строку
156-
- `toArray()` - возвращает массив элементов
157-
- `count()` - возвращает количество элементов
124+
data = [
125+
{"k1": 2, "k2": "x"},
126+
{"k1": 4, "k2": "z"},
127+
{"k1": 5, "k2": "p"},
128+
]
129+
println groupby(data, def(e) = e.k1) // {"2"=[{k1=2, k2=x}], "4"=[{k1=4, k2=z}], "5"=[{k2=p, k1=5}]}
130+
println groupby(data, def(e) = e.k2) // {"x"=[{k1=2, k2=x}], "z"=[{k1=4, k2=z}], "p"=[{k2=p, k1=5}]}
131+
- name: stream
132+
args: data
133+
desc: creates stream from data and returns `StreamValue`
134+
desc_ru: создаёт stream из данных и возвращает `StreamValue`
158135
- name: takewhile
159136
args: 'data, predicate'
160137
desc: 'takes elements while predicate function returns true'
161-
desc_ru: 'собирает элементы пока функция-предикат возвращает true'
138+
desc_ru: 'собирает элементы пока функция-предикат возвращает true'
139+
types:
140+
- name: StreamValue
141+
functions:
142+
- name: filter
143+
args: func
144+
desc: filters elements based on predicate function result (true - remain, false - drop)
145+
desc_ru: фильтрует элементы на основе результата функции-предиката (true - оставить, false - убрать)
146+
- name: filterNot
147+
args: func
148+
desc: filters elements based on negated predicate function result (false - remain, true - drop)
149+
desc_ru: фильтрует элементы на основе обратного результата функции-предиката (false - оставить, true - убрать)
150+
since: 2.0.0
151+
- name: map
152+
args: func
153+
desc: converts each element
154+
desc_ru: преобразует каждый элемент
155+
- name: flatMap
156+
args: func
157+
desc: converts each element to array
158+
desc_ru: преобразует каждый элемент в массив
159+
- name: sorted
160+
args: func
161+
desc: sorts elements with comparator function
162+
desc_ru: сортирует элементы в соответствии с функцией-компаратором
163+
- name: sortBy
164+
args: func
165+
desc: applies function, then sorts elements
166+
desc_ru: применяет функцию, затем сортирует элементы
167+
- name: groupBy
168+
args: func
169+
desc: groups elements based on function result
170+
desc_ru: группирует элементы на основе результата выполнения функции
171+
since: 2.0.0
172+
- name: takeWhile
173+
args: func
174+
desc: takes elements while predicate function returns true
175+
desc_ru: собирает элементы пока функция-предикат возвращает true
176+
- name: dropWhile
177+
args: func
178+
desc: skips elements while predicate function returns true, returns remaining elements
179+
desc_ru: пропускает элементы пока функция-предикат возвращает true
180+
- name: peek
181+
args: func
182+
desc: executes function for each element and returns stream
183+
desc_ru: вызывает функцию для каждого элемента и возвращает stream
184+
- name: skip
185+
args: count
186+
desc: skips `count` elements
187+
desc_ru: пропускает указанное количество элементов
188+
- name: limit
189+
args: count
190+
desc: limits elements size
191+
desc_ru: ограничивает количество элементов
192+
- name: custom
193+
args: func
194+
desc: performs custom operation
195+
desc_ru: выполняет пользовательскую операцию над данными
196+
example: |-
197+
use std, functional
198+
199+
println stream([1, 2, 3, 4])
200+
.custom(::reverse)
201+
.toArray()
202+
203+
def reverse(container) {
204+
size = length(container)
205+
result = newarray(size)
206+
for i : range(size) {
207+
result[size - i - 1] = container[i]
208+
}
209+
return result
210+
}
211+
- name: reduce
212+
args: func
213+
desc: converts elements to one value
214+
desc_ru: преобразует элементы в одно значение
215+
- name: forEach
216+
args: func
217+
desc: executes function for each element
218+
desc_ru: вызывает функцию для каждого элемента
219+
- name: forEachIndexed
220+
args: func
221+
desc: executes function for each element and its index
222+
desc_ru: вызывает функцию для каждого элемента и его порядкового номера
223+
since: 2.0.0
224+
- name: joining
225+
args: delimiter = "", prefix = "", suffix = ""
226+
desc: joins elements into a string
227+
desc_ru: склеивает элементы в строку
228+
- name: toArray
229+
args: ""
230+
desc: returns array of elements
231+
desc_ru: возвращает массив элементов
232+
- name: count
233+
args: ""
234+
desc: returns the elements count
235+
desc_ru: возвращает количество элементов

docs/src/modules/std.yml

Lines changed: 45 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ constants:
1111
- name: OwnLang
1212
typeName: map
1313
type: 4
14-
value: "{PLATFORM=android/desktop, VERSION=1.5.0_000000, VERSION_MAJOR=1, VERSION_MINOR=5, VERSION_PATCH=0}"
14+
value: "{PLATFORM=android/desktop, VERSION=2.0.1_000000, VERSION_MAJOR=2, VERSION_MINOR=0, VERSION_PATCH=1}"
1515
since: 1.4.0
1616
functions:
1717
- name: arrayCombine
@@ -76,11 +76,39 @@ functions:
7676
7777
echo(1, "abc") // выведет строку "1 abc" в консоль
7878
echo(1, 2, 3, 4, 5, "a", "b") // выведет строку "1 2 3 4 5 a b" в консоль"
79+
- name: exit
80+
args: status
81+
desc: terminates an application with provided status code. Non-zero values indicates abnormal termination
82+
desc_ru: завершает работу приложения с заданным кодом. Ненулевое значение означает завершение с ошибкой
83+
since: 2.0.0
84+
example: |-
85+
use std
86+
87+
println "Bye!"
88+
exit(0)
89+
example_ru: |-
90+
use std
91+
92+
println "До свидания!"
93+
exit(0)
7994
- name: getBytes
8095
args: input, charset = "UTF-8"
8196
desc: returns byte array of the string in the given charset
8297
desc_ru: возвращает массив байт строки в заданной кодировке
8398
since: 1.5.0
99+
- name: getenv
100+
args: key, defaultValue = ""
101+
desc: returns the value of the specified environment variable if it's exists, returns `defaultValue` otherwise
102+
desc_ru: возвращает значение указанной переменной среды, если такова существует. В противном случае возвращает `defaultValue`
103+
since: 2.0.0
104+
example: |-
105+
use std
106+
println getenv("JAVA_HOME")
107+
- name: getprop
108+
args: key, defaultValue = ""
109+
desc: returns the value of the system property if it's exists, returns `defaultValue` otherwise
110+
desc_ru: возвращает значение системного свойства, если оно существует. В противном случае возвращает `defaultValue`
111+
since: 2.0.0
84112
- name: indexOf
85113
args: "input, what, index = 0"
86114
desc: "finds first occurrence of `what` in string `input`, starting at position `index`"
@@ -97,6 +125,11 @@ functions:
97125
args: "x"
98126
desc: "returns length of string, array/map size or number of function arguments"
99127
desc_ru: "возвращает длину строки, размер массива/объекта или количество аргументов функции в зависимости от типа аргумента x"
128+
- name: nanotime
129+
args: ""
130+
desc: returns VM time source in nanoseconds for elapsed time purposes
131+
desc_ru: возвращает время виртуальной машины в наносекундах, для отсчёта затраченного времени
132+
since: 2.0.0
100133
- name: newarray
101134
args: "size..."
102135
desc: "creates array with `size`.\n`newarray(x)` - creates 1D array, `newarray(x,y)` - creates 2D array"
@@ -107,13 +140,18 @@ functions:
107140
println newarray(4) // [0, 0, 0, 0]
108141
println newarray(2, 3) // [[0, 0, 0], [0, 0, 0]]
109142
- name: parseInt
110-
args: "str, radix"
111-
desc: parses string into integer in the `radix`
112-
desc_ru: парсит строку в целое число с указанным основанием
143+
args: str, radix
144+
desc: parses the input string into an integer with `radix` base
145+
desc_ru: преобразует строку в целое число с указанным основанием
113146
- name: parseLong
114-
args: "str, radix"
115-
desc: parses string into long in the `radix`
116-
desc_ru: парсит строку в длинное целое число с указанным основанием
147+
args: str, radix
148+
desc: parses the input string into a long integer with `radix` base
149+
desc_ru: преобразует строку в длинное целое число с указанным основанием
150+
- name: parseDouble
151+
args: str
152+
desc: parses the input string into a double
153+
desc_ru: преобразует строку в вещественное число типа double
154+
since: 2.0.0
117155
- name: rand
118156
args: "from = 0, to = .."
119157
desc: |-

ownlang-parser/src/test/resources/modules/functional/groupby.own

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,17 @@
11
use std, functional
22

3+
def testGroupByKeys() {
4+
data = [
5+
{"k1": 1, "k2": "a"},
6+
{"k1": 2, "k2": "b"},
7+
{"k1": 3, "k2": "c"},
8+
]
9+
result = groupby(data, def(e) = e.k2)
10+
assertEquals([{"k1": 1, "k2": "a"}], result.a)
11+
assertEquals([{"k1": 2, "k2": "b"}], result.b)
12+
assertEquals([{"k1": 3, "k2": "c"}], result.c)
13+
}
14+
315
def testArraysGroupBy() {
416
arr = [1, 2, 3, 4, 1, 2, 3, 1, 2, 3]
517
result = groupby(arr, def(v) = v % 2 == 0)
@@ -13,3 +25,4 @@ def testMapsGroupBy() {
1325
assertEquals({"test1": 234, "test2": 345, "test3": 456}, result[true])
1426
assertEquals({"abc": 123, "def": 567}, result[false])
1527
}
28+

0 commit comments

Comments
 (0)