OILS / doc / ref / chap-builtin-func.md View on Github | oilshell.org

416 lines, 245 significant
1---
2in_progress: yes
3body_css_class: width40 help-body
4default_highlighter: oils-sh
5preserve_anchor_case: yes
6---
7
8Builtin Functions
9===
10
11This chapter in the [Oils Reference](index.html) describes builtin functions.
12
13(As opposed to [builtin commands](chap-builtin-cmd.html).
14
15<div id="toc">
16</div>
17
18## Values
19
20### len()
21
22Returns the
23
24- number of entries in a `List`
25- number of pairs in a `Dict`
26- number of bytes in a `Str`
27 - TODO: `countRunes()` can return the number of UTF-8 encoded code points.
28
29### type()
30
31Given an arbitrary value, returns a string representing the value's runtime type.
32
33For example:
34
35 var d = {'foo': 'bar'}
36 var n = 1337
37
38 $ = type(d)
39 (Str) 'Dict'
40
41 $ = type(n)
42 (Str) 'Int'
43
44### repeat()
45
46TODO:
47
48 = repeat('a', 3)
49 (Str) 'aaa'
50
51 = repeat(['a'], 3)
52 (List) ['a', 'a', 'a']
53
54Note that list elements are NOT copied. They are repeated by reference, which
55means the List can have aliases.
56
57 = repeat([[42]], 3)
58 (List) [[42], [42], [42]]
59
60Modeled after these Python expressions:
61
62 >>> 'a' * 3
63 'aaa'
64 >>> ['a'] * 3
65 ['a', 'a', 'a']
66
67
68## Conversions
69
70### bool()
71
72Returns the truth value of its argument. Similar to `bool()` in python, it
73returns `false` for:
74
75- `false`, `0`, `0.0`, `''`, `{}`, `[]`, and `null`.
76
77Returns `true` for all other values.
78
79### int()
80
81Given a float, returns the largest integer that is less than its argument (i.e. `floor()`).
82
83 $ = int(1.99)
84 (Int) 1
85
86Given a string, `Int()` will attempt to convert the string to a base-10
87integer. The base can be overriden by calling with a second argument.
88
89 $ = int('10')
90 (Int) 10
91
92 $ = int('10', 2)
93 (Int) 2
94
95 ysh$ = Int('foo')
96 # fails with an expression error
97
98### float()
99
100Given an integer, returns the corressponding flaoting point representation.
101
102 $ = float(1)
103 (Float) 1.0
104
105Given a string, `Float()` will attempt to convert the string to float.
106
107 $ = float('1.23')
108 (Float) 1.23
109
110 ysh$ = float('bar')
111 # fails with an expression error
112
113### str()
114
115Converts a `Float` or `Int` to a string.
116
117### list()
118
119Given a list, returns a shallow copy of the original.
120
121Given an iterable value (e.g. a range or dictionary), returns a list containing
122one element for each item in the original collection.
123
124 $ = list({'a': 1, 'b': 2})
125 (List) ['a', 'b']
126
127 $ = list(1:5)
128 (List) [1, 2, 3, 4, 5]
129
130### dict()
131
132Given a dictionary, returns a shallow copy of the original.
133
134### chr()
135
136(not implemented)
137
138Convert an integer to a Str with the corresponding UTF-8 encoded code point.
139
140Integers in the surrogate range are an error.
141
142 = chr(97)
143 (Str) 'a'
144
145 = chr(0x3bc)
146 (Str) 'μ'
147
148### ord()
149
150(not implemented)
151
152Convert a single UTF-8 encoded code point to an integer.
153
154 = ord('a')
155 (Int) 97
156
157 = ord('μ')
158 (Int) 956 # same as 0x3bc
159
160<!-- Do we have character literals like #'a' ? Or just use strings. Small
161string optimization helps. -->
162
163### runes()
164
165TODO: Explicit iterator over runes.
166
167## Str
168
169### strcmp()
170
171TODO
172
173### split()
174
175TODO
176
177If no argument is passed, splits by whitespace
178
179<!-- respecting Unicode space? -->
180
181If a delimiter Str with a single byte is given, splits by that byte.
182
183Modes:
184
185- Python-like algorithm
186- Is awk any different?
187- Split by eggex
188
189### shSplit()
190
191Split a string into a List of strings, using the shell algorithm that respects
192`$IFS`.
193
194Prefer `split()` to `shSplit()`.
195
196
197## List
198
199### join()
200
201Given a List, stringify its items, and join them by a separator. The default
202separator is the empty string.
203
204 var x = ['a', 'b', 'c']
205
206 $ echo $[join(x)]
207 abc
208
209 $ echo $[join(x, ' ')] # optional separator
210 a b c
211
212
213It's also often called with the `=>` chaining operator:
214
215 var items = [1, 2, 3]
216
217 json write (items => join()) # => "123"
218 json write (items => join(' ')) # => "1 2 3"
219 json write (items => join(', ')) # => "1, 2, 3"
220
221
222### any()
223
224Returns true if any value in the list is truthy (`x` is truthy if `Bool(x)`
225returns true).
226
227If the list is empty, return false.
228
229 = any([]) # => false
230 = any([true, false]) # => true
231 = any([false, false]) # => false
232 = any([false, "foo", false]) # => true
233
234Note, you will need to `source --builtin list.ysh` to use this function.
235
236### all()
237
238Returns true if all values in the list are truthy (`x` is truthy if `Bool(x)`
239returns true).
240
241If the list is empty, return true.
242
243 = any([]) # => true
244 = any([true, true]) # => true
245 = any([false, true]) # => false
246 = any(["foo", true, true]) # => true
247
248Note, you will need to `source --builtin list.ysh` to use this function.
249
250## Word
251
252### glob()
253
254See `glob-pat` topic for syntax.
255
256### maybe()
257
258## Math
259
260### abs()
261
262Compute the absolute (positive) value of a number (float or int).
263
264 = abs(-1) # => 1
265 = abs(0) # => 0
266 = abs(1) # => 1
267
268Note, you will need to `source --builtin math.ysh` to use this function.
269
270### max()
271
272Compute the maximum of 2 or more values.
273
274`max` takes two different signatures:
275
276 1. `max(a, b)` to return the maximum of `a`, `b`
277 2. `max(list)` to return the greatest item in the `list`
278
279For example:
280
281 = max(1, 2) # => 2
282 = max([1, 2, 3]) # => 3
283
284Note, you will need to `source --builtin math.ysh` to use this function.
285
286### min()
287
288Compute the minimum of 2 or more values.
289
290`min` takes two different signatures:
291
292 1. `min(a, b)` to return the minimum of `a`, `b`
293 2. `min(list)` to return the least item in the `list`
294
295For example:
296
297 = min(2, 3) # => 2
298 = max([1, 2, 3]) # => 1
299
300Note, you will need to `source --builtin math.ysh` to use this function.
301
302### round()
303
304### sum()
305
306Computes the sum of all elements in the list.
307
308Returns 0 for an empty list.
309
310 = sum([]) # => 0
311 = sum([0]) # => 0
312 = sum([1, 2, 3]) # => 6
313
314Note, you will need to `source --builtin list.ysh` to use this function.
315
316## Serialize
317
318### toJson()
319
320Convert an object in memory to JSON text:
321
322 $ = toJson({name: "alice"})
323 (Str) '{"name":"alice"}'
324
325Add indentation by passing the `space` param:
326
327 $ = toJson([42], space=2)
328 (Str) "[\n 42\n]"
329
330Similar to `json write (x)`, except the default value of `space` is 0.
331
332See [json-encode-err](chap-errors.html#json-encode-err) for errors.
333
334### fromJson()
335
336Convert JSON text to an object in memory:
337
338 = fromJson('{"name":"alice"}')
339 (Dict) {"name": "alice"}
340
341Similar to `json read <<< '{"name": "alice"}'`.
342
343See [json-decode-err](chap-errors.html#json-decode-err) for errors.
344
345### toJson8()
346
347Like `toJson()`, but it also converts binary data (non-Unicode strings) to
348J8-style `b'foo \yff'` strings.
349
350In contrast, `toJson()` will do a lossy conversion with the Unicode replacement
351character.
352
353See [json8-encode-err](chap-errors.html#json8-encode-err) for errors.
354
355### fromJson8()
356
357Like `fromJson()`, but it also accepts binary data denoted by J8-style `b'foo
358\yff'` strings.
359
360See [json8-decode-err](chap-errors.html#json8-decode-err) for errors.
361
362## Pattern
363
364### `_group()`
365
366Like `Match => group()`, but accesses the global match created by `~`:
367
368 if ('foo42' ~ / d+ /) {
369 echo $[_group(0)] # => 42
370 }
371
372### `_start()`
373
374Like `Match => start()`, but accesses the global match created by `~`:
375
376 if ('foo42' ~ / d+ /) {
377 echo $[_start(0)] # => 3
378 }
379
380### `_end()`
381
382Like `Match => end()`, but accesses the global match created by `~`:
383
384 if ('foo42' ~ / d+ /) {
385 echo $[_end(0)] # => 5
386 }
387
388## Introspection
389
390### `shvar_get()`
391
392TODO
393
394## Config Gen
395
396### Better Syntax
397
398These functions give better syntax to existing shell constructs.
399
400- `shquote()` for `printf %q` and `${x@Q}`
401- `lstrip()` for `${x#prefix}` and `${x##prefix}`
402- `rstrip()` for `${x%suffix}` and `${x%%suffix}`
403- `lstripglob()` and `rstripglob()` for slow, legacy glob
404- `upper()` for `${x^^}`
405- `lower()` for `${x,,}`
406- `strftime()`: hidden in `printf`
407
408
409## Codecs
410
411TODO
412
413## Hashing
414
415TODO
416