Any type

Any type is parent type of all types. All objects in NGS are of type Any. F(x) ... is same as F(x:Any) ...

Methods

!=(a:Any, b:Any) Source: stdlib.ngs:48
Inequality operator

Example

1 !=2  # true, same as not(1==2)
!==(a:Any, b:Any) Source: stdlib.ngs:55
Non-sameness operator

Example

h1 = {"a": 1}
h2 = {"a": 1}
h1 !== h2  # true, same as not(h1===h2)
h1 == h2   # true
!~(x:Any, pattern:Any) Source: stdlib.ngs:1248
Undocumented

Returns

not(x =~ pattern)
!~(x:Any, pattern:Any, mc:MatchContext) Source: stdlib.ngs:1250
Undocumented
%(x:Any, cb:Fun) Source: stdlib.ngs:1914
Each operator. Same as calling x.each(cb)

Example

[1,2,3,4] % echo
+?(a:Any, b:Any) Source: stdlib.ngs:1929
Return a+b unless one of the arguments is falsy. In that case return that argument (a if both are falsy). Useful for building strings with optional parts.

Returns

a+b or a or b

Example

status_detail = ' (' +? maybe_empty_array.join(',') +? ')'
echo("Status: ${main_status}${status_detail}")
->(pattern:Any, action:Any)experimental Source: stdlib.ngs:1235
Undocumented

Automatically called by NGS for syntax

pattern -> action
.(x:Any, f:Fun)EXPERIMENTAL Source: stdlib.ngs:804
Undocumented

Automatically called by NGS for syntax

x.{ ... }

Returns

f(x)
.(hl:HashLike, k:Any) Source: stdlib.ngs:2249
Get value by key. Throws KeyNotFound.

Automatically called by NGS for syntax

your_hashlike.literal_key

Returns

Any
.(hl:DeprecatedTopLevelHashlike, k:Any) Source: stdlib.ngs:2357
Get value by key. Throws KeyNotFound.

Automatically called by NGS for syntax

your_hashlike.literal_key

Returns

Any
..(start:Any, end:Any) Source: stdlib.ngs:2869
Constructs open-open predicate range

Returns

PredRange

Example

[10,200,300,40,50][(X==10)..(X==40)]          # [200, 300]
["abc", "aaa", "bbb", "def"][/^abc/../^def/]  # ["aaa", "bbb"]
..(start:Any, end:Any) Source: stdlib.ngs:2883
Constructs closed-open numerical range

Parameters

startnumerical or null (at least one of start or end must be non-null)
endnumerical or null (at least one of start or end must be non-null)

Returns

NumRange

Example

(1..4).sum()  # 6
...(start:Any, end:Any) Source: stdlib.ngs:2875
Constructs closed-closed predicate range

Returns

PredRange

Example

[10,200,300,40,50][(X==10)...(X==40)]          # [10,200,300,40]
["abc", "aaa", "bbb", "def"][/^abc/.../^bbb/]  # ["abc", "aaa", "bbb"]
...(start:Any, end:Any) Source: stdlib.ngs:2891
Constructs closed-closed numerical range

Returns

NumRange

Example

(1...4).sum()  # 10
.=(obj:NormalType, field:Str, v:Any)
Set NormalType (a type that is typically defined by user) field. Throws FieldNotFound.

Automatically called by NGS for syntax

obj.field = v

Parameters

fieldField to set. Currently only "user" is supported.

Returns

v
.=(obj:NormalTypeInstance, field:Str, v:Any)
Set Normal type (a type that is typically defined by user) instance field

Automatically called by NGS for syntax

obj.field = v

Returns

v

Example

type T; t=T(); t.x=1
.=(h:Hash, field:Str, v:Any) Source: stdlib.ngs:950
Set hash key.

Returns

v

Example

h = {"a": 1}
h.a = 2  # 2, Same as h["a"] = 2
.=(hl:HashLike, k:Any, v:Any) Source: stdlib.ngs:2254
Set value.

Automatically called by NGS for syntax

your_hashlike.literal_key = v

Returns

v
.=(hl:DeprecatedTopLevelHashlike, k:Any, v:Any) Source: stdlib.ngs:2368
Set value.

Automatically called by NGS for syntax

your_hashlike.literal_key = v

Returns

v
/(x:Any, mapper:Fun) Source: stdlib.ngs:1909
Map operator. Same as calling x.map(mapper)

Example

[1,2,3,4] / F(x) x * 10
::(nti:NormalTypeInstance, k:Any) Source: stdlib.ngs:445
Get NormalType object field. Useful when calling method stored in an field.

Example

myobj::method_in_field(arg)  # calls method stored in myobj.method_in_field
(myobj.method_in_field)(arg) # calls method stored in myobj.method_in_field
myobj.method_in_field(arg)   # calls global "method_in_field"
::(h:Hash, k:Any) Source: stdlib.ngs:451
Get Hash key. Useful when calling method stored in a Hash key. Useful for working with namespaces, which are implemented as Hash instances.

Example

elb = AWS::Elb(...).converge(...)
::(x:Any, f:Fun) Source: stdlib.ngs:461
Executes f(x)

Returns

x
::=(nti:NormalTypeInstance, k:Any, v:Any) Source: stdlib.ngs:454
Set NormalType object field. It's implemented to complete the :: operator. There is no particular use case.
::=(h:Hash, k:Any, v:Any) Source: stdlib.ngs:456
Set Hash key. It's implemented to complete the :: operator. There is no particular use case.
==(a:Any, b:Any)
Always false. Other == method implementations should compare types they understand. If none of them can handle the comparison, objects are considered non-equal.

Returns

false
===(a:Any, b:Any)
Sameness comparison.
=~(x:Any, pattern:Any) Source: stdlib.ngs:1206
Undocumented
=~(x:Any, pattern:Any, _mc:MatchContext) Source: stdlib.ngs:1219
Fallback for pattern matching. Throws NotImplemented.
=~(x:Any, pa:PatternAction, mc:MatchContext)experimental Source: stdlib.ngs:1239
Undocumented
=~(x:Any, bti:BasicTypeInstance, _mc:MatchContext) Source: stdlib.ngs:1253
Undocumented

Returns

x == bti
=~(x:Any, c:Capture, mc:MatchContext)internal Source: stdlib.ngs:1283
Undocumented
=~(x:Any, ie:IfExists, mc:MatchContext) Source: stdlib.ngs:1315
Undocumented
=~(x:Any, b:Branch, mc:MatchContext)internal Source: stdlib.ngs:1333
Returns result of (=~)(x, b.pattern, mc)

Returns

Bool
=~(x:Any, t:Transformed, mc:MatchContext) Source: stdlib.ngs:1354
Undocumented
=~(x:Any, h:Hash, mc:MatchContext) Source: stdlib.ngs:1368
Checks whether object fields (or Hash keys) named after h keys match (=~) the corresponding h values. Key of type Str, Int or Real: the field must exist (unless the value is IfExists) and match. Key that is a pattern (other than Branch or Each): some field whose name matches the key must match. Key that is Each(pattern): every field whose name matches the pattern must match. Key that is Branch(pattern): every field whose name matches the pattern is tried, always matches. Inspired by underscorejs' "matcher"
=~(x:Any, a:Arr, mc:MatchContext) Source: stdlib.ngs:1416
Checks that 1. The x is Eachable1 but not Str or Int 2. Each element of x matches (=~) corresponding element in a (If number of elements does not match - there is no match)
=~(x:Any, f:Fun, _mc:MatchContext) Source: stdlib.ngs:1433
Undocumented

Returns

f(x).Bool()
=~(x:Any, t:Type, _mc:MatchContext) Source: stdlib.ngs:1437
Check whether x is of type t

Returns

x is t
=~(x:Any, l:Lit, _mc:MatchContext) Source: stdlib.ngs:1440
Check whether x is the literal value l (using ==)
=~(x:Any, n:Not, mc:MatchContext) Source: stdlib.ngs:1490
Negate the match

Returns

Bool
=~(x:Any, ap:AtPath, mc:MatchContext)internal Source: stdlib.ngs:1507
Do not use directly!
=~(x:Any, rp:ResetPath, mc:MatchContext)experimental Source: stdlib.ngs:1561
Undocumented
=~(x:Any, a:AnyOf, mc:MatchContext) Source: stdlib.ngs:2141
Check whether one of the patterns (elements of AnyOf) matches

Example

{"k1": "v1", "k2": "v2", "k3": "v3"}.filterk(AnyOf("k1", "k3"))  # {"k1": "v1", "k3": "v3"}
=~(x:Any, a:AllOf, mc:MatchContext) Source: stdlib.ngs:2208
Checks whether all of the patterns (elements of AllOf) match

Example

{"k1": "v1", "k2": "v2", "kk3": "vv3"}.filterk(AllOf(/^k/, {len(A) <= 2})) == %{k1 v1 k2 v2}
=~(x:Any, nr:NumRange, _mc:MatchContext) Source: stdlib.ngs:2965
Checks whether x is in the range.

Example

1 =~ 0..5  # true
=~(x:Any, p:Present, mc:MatchContext) Source: stdlib.ngs:4771
Checks element presence.

Returns

Bool

Example

[1,2,3] =~ Present(3)  # MatchSuccess
=~(x:Any, a:Absent, mc:MatchContext) Source: stdlib.ngs:4794
Checks element absence.

Returns

Bool

Example

[1,2,3] =~ Absent(0)  # MatchSuccess
=~(x:Any, cp:CommandsPipeline, _mc:MatchContext) Source: stdlib.ngs:7669
A value that is not a commands pipeline, process or DecodeHints does not match a commands pipeline pattern.
=~(x:Any, pfx:Pfx, mc:MatchContext) Source: stdlib.ngs:8227
Undocumented

Example

[1,2,3] =~ Pfx([1,2])
=~(x:Any, sfx:Sfx, mc:MatchContext) Source: stdlib.ngs:8256
Undocumented

Returns

Bool

Example

[1,2,3] =~ Sfx([2,3])
=~(x:Any, s:SubSeq, _mc:MatchContext) Source: stdlib.ngs:8289
Checks subsequence presence

Parameters

sSubSeq of Str

Returns

Bool
=~(x:Any, r:RegExp, mc:MatchContext)internal Source: stdlib.ngs:8485
Checks for RegExp match. Updates MatchContext.

Returns

Checks whether the argument is of type Str and matches (~) r

Example

%[w1 w2].filter(/1/)  # %[w1]
?(x:Any, pattern:Any) Source: stdlib.ngs:1904
Filter operator. Same as calling x.filter(pattern)

Example

[1,2,3,4] ? F(x) x > 2  # [3,4]
[](h:Hash, k:Any)
Get hash value by key. Throws KeyNotFound.

Returns

Any

Example

h = {"a": 1}
h["a"]  # 1
h["b"]  # KeyNotFound exception thrown
[](hl:HashLike, k:Any) Source: stdlib.ngs:2240
Get value by key. Throws KeyNotFound.

Automatically called by NGS for syntax

your_hashlike[k]
[](hl:DeprecatedTopLevelHashlike, k:Any) Source: stdlib.ngs:2337
Get value by key. Throws KeyNotFound.

Automatically called by NGS for syntax

your_hashlike[k]
[]=(arr:Arr, idx:Int, v:Any)
Set element at the given index or throw IndexNotFound if the index is out of range.

Returns

v
[]=(h:Hash, k:Any, v:Any)
Set hash value.

Parameters

hTarget hash
kKey
vValue

Returns

v

Example

h = {"a": 1}
h["a"] = 2
h["a"]  # 2
[]=(al:ArrLike, idx:Int, x:Any) Source: stdlib.ngs:2063
Set element in the underlying array.
[]=(hl:HashLike, k:Any, v:Any) Source: stdlib.ngs:2244
Set value.

Automatically called by NGS for syntax

your_hashlike[k] = v
[]=(hl:DeprecatedTopLevelHashlike, k:Any, v:Any) Source: stdlib.ngs:2347
Set value.

Automatically called by NGS for syntax

your_hashlike[k] = v
[]=(arr:Arr, idx:Int, val:Any) Source: stdlib.ngs:3602
Set array element by index from the end (negative indexes handler). Throws IndexNotFound if abs(idx) > len(arr).

Parameters

idxNegative index

Example

a = [1, 2, 3]; a[-1] = 99  # [1, 2, 99]
[]=(h:Hash, k:Any, v:Any)
Setting same key twice is a bug. If it happens, augment_types() works on one objects but other objects are used later.
\(x:Any, f:Fun)deprecated Source: stdlib.ngs:1921
Deprecated. Use expr.f() and expr.{ your_code } Call operator. Same as calling f(x)

Example

[1,2,3,4] \ echo
all(e:Eachable1, pattern:Any=method) Source: stdlib.ngs:3245
Check whether all elements in arr satisfy the given pattern.

Parameters

eThe items to check
patternTest function or anything else acceptable by (=~), defaults to Bool.constructors

Returns

Bool

Example

[1,2,3].all(X<10)   # true
[1,2,10].all(X>5)   # false
any(e:Eachable1, pattern:Any=method) Source: stdlib.ngs:3226
Check whether there is any element in e that satisfies the given pattern.

Parameters

eThe items to check
patternTest function or anything else acceptable by (=~), defaults to Bool.constructors

Returns

Bool

Example

[1,2,10].any(F(elt) elt > 5)   # true
[1,2,10].any(F(elt) elt > 15)  # false
ArgvMatcher(option:Str, value:Any, f:UserDefinedMethod) Source: autoload/globals/ArgvMatcher.ngs:27
Sets ARGV matching option.

Parameters

optionOption name. The only supported option at this time is "positionals".
valueOption value.

Example

# Any command line argument that is not "allreg" goes to "filters" parameters.
ArgvMatcher('positionals', 'filters') do
F main(filters:Arr, allreg:Bool=false) ...
assert(val:Any, pattern:Any, msg:Str='Assertion failed') Source: stdlib.ngs:333
Throws AssertFail with given message if val does not match the pattern

Returns

val

Example

my_template.get('concept', []).assert(Arr)
assert(loginResult, {'access_token': Str}, "access_token must be present in response")
assert(val:Any, pattern:Any, e:Exception) Source: stdlib.ngs:345
Throws e with given message if val does not match the pattern

Returns

val
assert(val:Any, pattern:Any, f:Fun) Source: stdlib.ngs:357
Throws whatever f(val) returns if val does not match the pattern

Returns

val

Example

assert(n, Int, { InvalidArgument("n must be integer").set('n', n) })
assert(val:Any, msg:Str='Assertion failed') Source: stdlib.ngs:361
Throws AssertFail with given message if val is falsy

Parameters

valif evaluates to false, causes AssertFail exception
msgmessage for the exception, defaults to "Assertion failed"

Returns

val

Example

my_array=[]
# ... Code that adds elements to my_array ...
assert(my_array.len() > 3, "my_array must have more than 3 elements")  # AssertFail exception, with the given message
assert_array(actual:Any, title:Str=null) Source: autoload/globals/test.ngs:107
Assert actual is an Arr. Throws TestFail.

Returns

actual
assert_base(actual:Any, expected:Any, comparison:Any, display_comparison:Any, title:Str, ok_prefix:Any='')internal Source: autoload/globals/test.ngs:41
A helper used by other assert_* methods. Please do not use directly.
assert_bool(actual:Any, title:Str=null) Source: autoload/globals/test.ngs:85
Assert actual is a Bool. Throws TestFail.

Returns

actual
assert_eq(actual:Any, expected:Any, title:Str=null) Source: autoload/globals/test.ngs:52
Assert equality. Throws TestFail.

Returns

actual

Example

test("Heavy load on instance", {
  # do the load
  assert_eq(`curl -m 1 192.168.10.10/health`, 'OK')
})
assert_has(actual:Any, expected:Any, title:Str=null) Source: autoload/globals/test.ngs:208
Assert having specific element or substring (checks with "has"). Throws TestFail.

Returns

actual

Example

assert_has("abc", "xyz")  # Throws TestFail
assert_has([1,2,3], 3)    # OK
assert_hash(actual:Any, title:Str=null) Source: autoload/globals/test.ngs:97
Assert actual is a Hash. Throws TestFail.

Returns

actual
assert_hash_keys(actual:Any, expected:Arr, title:Str='Must be a hash with keys') Source: autoload/globals/test.ngs:127
Assert actual is a Hash and it has the expected keys. Throws TestFail.

Returns

actual

Example

assert_hash_keys({}, ['kk'])  # Throws TestFail.
assert_hash_keys({'kk': 7}, ['kk'])  # OK
assert_hash_keys_values(actual:Any, expected:Hash, title:Str='Must be a hash with keys and values') Source: autoload/globals/test.ngs:143
Assert actual is a Hash and it has the expected keys with expected values. Throws TestFail.

Returns

actual

Example

assert_hash_keys_values({'kk': 7}, {'ll': 7})  # Throws TestFail
assert_hash_keys_values({'kk': 7, 'll': 8}, {'kk': 7})  # OK
assert_in(actual:Any, expected:Any, title:Str=null) Source: autoload/globals/test.ngs:65
Assert element is in an array (or other Eachable1). Throws TestFail.

Returns

actual

Example

assert_in(10, [10, 2], "test in")
assert_match(actual:Any, expected:Any, title:Str=null) Source: autoload/globals/test.ngs:75
Assert actual matches expected. Throws TestFail.

Returns

actual

Example

assert_match("abc", /^a/, "test match") == "abc"
assert_min_len(actual:Any, expected:Any, title:Str=null) Source: autoload/globals/test.ngs:161
Assert actual is of at least specified length. Throws TestFail.

Returns

actual
assert_path_exists(p:Any, title:Str='Check that path exists') Source: autoload/globals/test.ngs:231
Assert given path exists.

Parameters

pStr or Path

Returns

p
assert_resolvable(h:Str, title:Str='Check that host is resolvable', times:Any=45, sleep:Any=2, check:Any=method) Source: autoload/globals/test.ngs:219
Assert given host is resolvable. Uses "dig" command line utility. Retries "times" times, sleeping "sleep" seconds in between. Throws TestFail.

Returns

don't count on return value

Example

assert_resolvable("my_new_host.example.com")
assert_string(actual:Any, title:Str=null) Source: autoload/globals/test.ngs:117
Assert actual is a string. Throws TestFail.

Returns

actual
Bool(x:Any)
Convert to Bool. Str, Arr and Hash of non-zero size return true. Bool returns as is. Null returns false. Int returns true if it is not zero.

Parameters

xBool or Int or Str or Arr or Hash or Null

Returns

Bool
bootstrap_print_compilation_warnings(program_bytecode:Any, fname:Any) Source: stdlib.ngs:9477
Undocumented
Box(x:Any) Source: stdlib.ngs:4609
Convert anything to Box (always FullBox)

Parameters

xvalue to enclose in a box

Returns

FullBox with given value

Example

Box(7).map(X*2).get()  # 14
Box(h:Hash, k:Any) Source: stdlib.ngs:4648
Convert hash value indexed by the given key to a Box

Parameters

kkey to look in hash

Returns

Box. FullBox if the hash has the element referenced by k, EmptyBox otherwise.

Example

my_hash = {"a": 10, "b": 300}
my_hash.Box("a").map(X*2).each(echo)
# output: 20
my_hash.Box("nope").map(X*2).each(echo)
# no output
c_pthread_create(attr:c_pthread_attr_t, start_routine:UserDefinedMethod, arg:Any)
Call PTHREAD_CREATE(3). Not recommended for direct calls, use Thread type instead.

Returns

Arr with [Int, c_pthread_t]. Int is the status returned by pthread_create(). c_pthread_t is a thin wrapper around underlying pthread_t, returned by PTHREAD_CREATE(3)

Example

F init(t:Thread, f:Fun, arg) {
	thread_attr = c_pthread_attr_t()
	c_pthread_attr_init(thread_attr)
	create_result = c_pthread_create(thread_attr, f, arg)
	code = create_result[0]
	if code {
		throw Error("Failed to c_pthread_create")
	}
	t.thread = create_result[1]
}
can(val:Any, fun:Fun) Source: stdlib.ngs:1011
Checks whether fun(val) throws

Returns

Bool - true when fun does not throw

Example

"10".can(Int)   # true
"abc".can(Int)  # false
cell_display_width(x:Any) Source: autoload/globals/Table.ngs:21
Calculate cell display width - any Str()-able object
code(e:Any)
Security implications. Not to expose possible secrets (such as AWS_...) Do not remove unless you have alternative solution.
config(k:Str, v:Any) Source: stdlib.ngs:8087
Set configuration. To be used with config(k:Str).

Example

config('table_Instances', %[InstanceId tag_Name tag_env tag_role IPs InstanceType State KeyName SecurityGroups AZ RestOfTags])
count(e:Eachable1, pattern:Any=method) Source: stdlib.ngs:3392
Count number of items that match the pattern.

Parameters

eItems to look at
patternTest function or anything else acceptable by (=~), defaults to Bool.constructors

Returns

Int

Example

[1,2,3,11,12].count(X>10)  # 2
debug(str_or_producer:Any) Source: stdlib.ngs:5974
Same as debug('default', str_or_producer)
debug(facility:Str, str_or_producer:Any) Source: stdlib.ngs:5982
Debug to standard error. "DEBUG" environment variable must be non-empty string to activate. Otherwise nothing is outputted. TODO: Exclude thread ID if there is only one thread. TODO: Timestamps? Timestamps acquiring might not be safe after fork before exec.

Parameters

str_or_producerThe message. If str_or_producer is a Fun, the result of str_or_producer() is the message; it is called only when debug is enabled for the facility.
decode(value:Any, t:Type) Source: stdlib.ngs:2557
Resolve named instance of t by uniquely-identifying value of any field

Example

echo("RED".decode(Color))   # <Color numval=4 name=RED>
deep_copy(x:Any) Source: stdlib.ngs:7
Return as is for Int, Real, Bool, Null
del(h:Hash, k:Any)
Delete hash key. Throws KeyNotFound if k is not in h. WARNING: this method will probably be renamed to "delete" in future versions.

Parameters

hTarget hash
kKey

Returns

h

Example

h={"a": 1}; h.del("a"); h  # {}
h={}; h.del("a"); # KeyNotFound exception
h={"a": 1, "b": 2}; h.del("a"); h  # {"b": 2}
del(hl:HashLike, k:Any) Source: stdlib.ngs:2304
Remove k from hl

Returns

hl
dflt(i:NormalTypeInstance, k:Any, v:Any) Source: stdlib.ngs:901
Set object field if it's not already set

Parameters

vThe value to set when k is not set. If v is a Fun, the result of v(k) is set instead, only when k is not set.

Returns

Field value, the already-existed or new.

Example

my_something.dflt(k, []).push(elt)
dflt(s:Success, x:Any) Source: stdlib.ngs:1044
Undocumented

Returns

s
dflt(f:Failure, x:Any) Source: stdlib.ngs:1047
Undocumented

Returns

Value(x,f)
dflt(e:Eachable1, k:Any, v:Any) Source: stdlib.ngs:2737
Set a field on all elements if it's not already set

Parameters

eEachable1

Returns

e

Example

my_items.dflt("source", "(unknown)")
dflt(hl:HashLike, k:Any, v:Any) Source: stdlib.ngs:2746
Set a key if it's not already set

Returns

Key value, the already-existed or new.

Example

mysomething.dflt(k, []).push(elt)
dflt(h:Hash, k:Any, v:Any) Source: stdlib.ngs:4430
Set a key in a Hash if it's not already set

Parameters

vThe value to set when k is not in h. If v is a Fun, v(k) is set instead, only when k is not in h.

Returns

Hash value, the already-existed or new.

Example

my_hash.dflt(k, []).push(elt)
dflt(fb:FullBox, x:Any) Source: stdlib.ngs:4661
Do nothing

Returns

fb

Example

my_array = [10, 20]
# dflt on FullBox has no effect
my_array.Box(1).dflt(100).map(X*2).each(echo) # HERE
# output: 40
# dflt on EmptyBox creates FullBox with the given value
my_array.Box(5).dflt(100).map(X*2).each(echo)
# output: 200
dflt(eb:EmptyBox, x:Any) Source: stdlib.ngs:4674
Wrap x in a Box

Parameters

xThe value for the FullBox. If x is a Fun, the result of x() is used instead.

Returns

FullBox(Value(x))

Example

my_array = [10, 20]
# dflt on FullBox has no effect
my_array.Box(1).dflt(100).map(X*2).each(echo)
# output: 40
# dflt on EmptyBox creates FullBox with the given value
my_array.Box(5).dflt(100).map(X*2).each(echo) # HERE
# output: 200
die(s:Str, status:Any=1) Source: stdlib.ngs:6031
Write message in s to standard error and exit, printing backtrace

Parameters

statusconverted to exit code using ExitCode()
dir(dirname:Str, subtype:Any=false, **kwargs:Hash) Source: stdlib.ngs:6247
List directory contents. Warning: "." and ".." are included. Throws DirFail when directory can not be listed.

Parameters

subtypeSelect type of returned items: true for Path sub-type, false for Path type

Returns

Arr of Path or it's sub-type

Example

dir("tmp/v8", true).filter(File)  # [ ..., <File path=tmp/v8/README.md fd=null>, <File path=tmp/v8/LICENSE.valgrind fd=null>, ... ]
dir("tmp/v8", true).filter(Dir)   # [ ..., <Dir path=tmp/v8/tools>, <Dir path=tmp/v8/infra>, ... ]
dir(dirname:Str, cb:Fun, subtype:Any=false, raw:Any=false) Source: stdlib.ngs:6257
List directory contents and call cb with Path() of each found item. "." and ".." are excluded.

Returns

unspecified at this time, do not count on it

Example

's=Stats(); dir("tmp/v8", {s.push(A.Type().name)}, true); s  # <Stats: {File=23, Dir=16}>'
drop(e:Eachable1, pattern:Any)experimental Source: stdlib.ngs:1810
EXPERIMENTAL! Do not use! Filters out items that match the pattern at the beginning of e.

Example

[1,2,3,1,2].drop(X<3)  # [3,1,2]
dump(obj:Any)
Low-level data structure dump. Used for debugging NGS itself.
duplicates(e:Eachable1, field_or_callback:Any) Source: stdlib.ngs:4407
Group the items from e and return groups of more than one element

Returns

Arr of Arr
echo(x:Any) Source: stdlib.ngs:3802
Echo non-string. Converts x to string first, using Str()

Parameters

xAnything but Str

Returns

null

Example

echo(1)
echo(dst:Any, lines:Lines) Source: stdlib.ngs:8576
Echo all lines to dst
echo_cli(x:Any)experimental Source: stdlib.ngs:9735
Echo the value before exiting the program, when the value is a result of evaluating the whole program
echo_cli(x:Any)experimental Source: stdlib.ngs:9740
Echo the value as JSON before exiting the program, when the value is a result of evaluating the whole program
echo_to(data:Any, target:Any) Source: stdlib.ngs:9343
Same as echo(target, data)
encode(data:Any, hints:Hash={}) Source: stdlib.ngs:7772
Encode data as JSON if hints say that "filename" ends with ".json"

Returns

Str
encode_json(obj:Any)
Encode JSON (serialize a data structure to JSON)

Returns

Str

Example

encode_json({"a": 1+1})  # The string { "a": 2 }
encode_json(x:Any, hints:Hash={}) Source: stdlib.ngs:9357
Convert data structure into JSON compatible data using JsonData and call built-in encode_json(). Implement JsonData() for your own types to customize converting to JSON.

Parameters

hintsHash, set 'pretty' to true to pretty-print the JSON

Returns

Str
ensure(x:Any, pat:Any, how:Any)experimental Source: stdlib.ngs:1657
EXPERIMENTAL! Do not use! Ensures that value matches pattern. If the value matches, it is returned as is. If not, Value(how, x) is used instead. In this case, there is assert() to see that the new value is matching pat.

Example

ensure(param, Str, encode_json)
ensure(x:Any, t:Type)experimental Source: stdlib.ngs:1982
EXPERIMENTAL! Do not use! Makes sure returned value is of type t. If x is already of type t, returns x. Otherwise, returns object of type t with single item x.

Parameters

ta subtype of Eachable1

Returns

Object of type t
ensure_array(x:Any)deprecated Source: stdlib.ngs:3929
Optionally, wrap x in an array. Return x if it's already Arr. Deprecated. Use ensure(x, Arr) instead.

Returns

Arr

Example

ensure_array([1,2])  # [1,2]
ensure_array("aa")   # ["aa"]
exit(status:Any=1) Source: stdlib.ngs:6035
Exit with given status

Parameters

statusconverted to exit code using ExitCode()
exit(s:Str, status:Any=1) Source: stdlib.ngs:6039
Write message in s to standard error and exit

Parameters

statusconverted to exit code using ExitCode()
ExitCode(x:Any) Source: stdlib.ngs:188
Undocumented

Returns

always 0
fetch(f:MaybeFile, decode_hints:Hash={}, dflt:Any=null) Source: autoload/globals/MaybeFile.ngs:17
Fetches the file using previously defined fetch()

Returns

Like fetch(File, ...) or dflt if the file is not present.
fields(e:Eachable2, pattern:Any) Source: stdlib.ngs:4215
Only keep fields matching the pattern. Same as e.filterk(pattern). In some other languages, similar functionality is called "project".

Example

{"a": 1, "b": 2}.fields(AnyOf("a", "a2"))  # {"a": 1}
fields(e:Eachable1, pat:Any) Source: stdlib.ngs:4236
Only keep specified fields in each element of e In some other languages, similar functionality is called "project".

Example

[{"a": 1, "b": 2}].fields(%[a])  # [{"a": 1}]
filter(s:Success, pattern:Any=method) Source: stdlib.ngs:1070
Check whether wrapped value matches the pattern.

Returns

s or Failure

Example

Success(10).filter(X>5)   # <Success val=10>
Success(10).filter(X>15)  # <Failure val=<ResultFail ...>>
filter(f:Failure, pattern:Any=method) Source: stdlib.ngs:1081
No-op, returns f

Returns

f

Example

Failure("blah").filter(X>5)  # <Failure val=blah>
filter(e:Eachable1, pattern:Any=method) Source: stdlib.ngs:1664
Filter e using pattern.

Parameters

eEachable1. WARNING: instances of same type as e must have empty constructor and push() method.
patternWhen item =~ pattern returns true, the item will appear in the resulting array.

Returns

Of same type as e

Example

(1...10).filter(F(num) num % 2 == 0)  # Gives [2,4,6,8,10]
(1...10).filter(X<5)  # Gives [1,2,3,4]
filter(fb:FullBox, pattern:Any=method) Source: stdlib.ngs:4560
Conditionally convert FullBox to EmptyBox.

Parameters

patternTest function or anything else acceptable by =~ to be called with the value in the FullBox, defaults to Bool.constructors

Returns

Box. fb if pattern succeeds, EmptyBox if not.

Example

Box(10).filter(X>5)   # <FullBox val=10>
Box(10).filter(X>20)  # <EmptyBox>
filter(d:Dir, pattern:Any) Source: stdlib.ngs:6298
Filter entries in d

Returns

Arr

Example

parent_dir.filter(Dir).each(F(sub_dir) echo(sub_dir))
filter(i:Iter, pattern:Any) Source: autoload/globals/Iter.ngs:183
EXPERIMENTAL! Do not use!
filter(ds:DelimStr, pattern:Any) Source: autoload/globals/DelimStr.ngs:19
Get new DelimStr with some elements filtered out

Example

DelimStr("/bin:/usr/bin:/usr/local/bin").filter(/usr/).Str()  # "/usr/bin:/usr/local/bin"
filterk(h:Eachable2, pattern:Any=method) Source: stdlib.ngs:4127
Filter hash by keys, keeping matched

Example

{"a": 1, "b": 2, "ccc": 3}.filterk(/^.$/)    # {a=1, b=2}
{"aa": 1, "ab": 2, "ba": 3}.filterk(/^a/)    # {aa=1, ab=2}
{"aa": 1, "ab": 2, 10: 3}.filterk(Int)       # {10=3}
{10: "a", 20: "b", 30: "c"}.filterk(X > 10)  # {20=b, 30=c}
filtero(mm:MultiMethod, pattern:Any) Source: stdlib.ngs:524
Undocumented
filterv(h:Eachable2, pattern:Any=method) Source: stdlib.ngs:4145
Filter hash by values

Example

{"a1": 1, "a2": 2, "b1": 10}.filterv(X>5)  # {"b1": 10}
finished_ok(program_name:Str, ok:Any)experimental Source: stdlib.ngs:6959
Undocumented
first(e:Eachable1, pattern:Any=method, dflt:Any=block) Source: stdlib.ngs:1701
Find first element in e that matches the pattern.

Parameters

patternTest function or anything else acceptable by =~, defaults to Bool.constructors
dfltDefault value. If dflt is a Fun, the result of dflt() is used instead.

Returns

Either the element or Value(dflt) if element was not found.

Example

(10..20).first(F(x) x % 3 == 0)        # 12 - first item divisible by 3
(10..20).first(F(x) x % 50 == 0, 1000) # 1000
[false, 0, null, "xyz", 100].first()  # "xyz"
[].first()                            # ElementNotFound exception
get(h:Hash, k:Any, dflt:Any)
Get hash value by key or dflt if it does not exist

Returns

Any

Example

h = {"a": 1}
h.get("a", 10)  # 1
h.get("b", 10)  # 10
get(h:Hash, k:Any, dflt:Any=null) Source: stdlib.ngs:953
Get hash value by key or Value(dflt, k) if it does not exist

Parameters

dfltDefault value, defaults to null. If dflt is a Fun, the result of dflt(k) is used instead.

Returns

h[k] or Value(dflt, k)

Example

h = {"a": 1}
h.get("a")  # 1
h.get("b")  # null
h.get("b", 10)  # 10
h.get("b", { 10 })  # 10
get(s:Success, dflt:Any) Source: stdlib.ngs:1036
Gets wrapped value

Returns

Any

Example

{ 1 / 10 }.Result().get(100)  # 0
get(f:Failure, dflt:Any) Source: stdlib.ngs:1041
Returns Value(dflt)

Parameters

dfltDefault value. If dflt is a Fun, the result of dflt() is used instead.

Example

{ 1 / 0 }.Result().get(100)  # 100
get(al:ArrLike, idx:Int, dflt:Any) Source: stdlib.ngs:2066
Get element at the given index or return dflt if the index is out of range (element at the given index does not exist). See get(Arr).
get(hl:HashLike, k:Any, dflt:Any) Source: stdlib.ngs:2258
Get value by key or dflt if it does not exist

Returns

Any
get(hl:HashLike, k:Any) Source: stdlib.ngs:2262
Get value by key or null if it does not exist

Returns

Any
get(e:Eachable1, field:Str, dflt:Any) Source: stdlib.ngs:3141
Return array made of given field of each element of given Eachable1 where present or default value where the field is not present.

Returns

Arr

Example

[{"x": 1}, {"y": 2}].get("x", null)  # [1, null]
get(a:Arr, idx:Int, dflt:Any=null) Source: stdlib.ngs:3152
Get element at the given index or return dflt if the index is out of range (element at the given index does not exist)

Parameters

dfltDefault value, defaults to null. If dflt is a Fun, the result of dflt(idx) is used instead.

Returns

a[idx] or Value(dflt, idx)

Example

[1,2,3].get(0, 10)    # 1
[1,2,3].get(5, 10)    # 10
[11].get(-1)          # 11
[10,20].get(-5, "X")  # "X"
get(fb:FullBox, dflt:Any=null) Source: stdlib.ngs:4577
Get FullBox value

Returns

Any

Example

Box(10).get()  # 10
get(eb:EmptyBox, dflt:Any) Source: stdlib.ngs:4592
Get EmptyBox value

Parameters

dfltDefault value. If dflt is a Fun, the result of dflt() is used instead.

Returns

Value(dflt)

Example

EmptyBox().get(10)  # 10
EmptyBox().get({ 5 + 5 })  # 10
get(dv:DynVar, dflt:Any) Source: stdlib.ngs:5857
Get the innermost bound value

Returns

The value, or dflt when nothing is bound
get(ms:MatchSuccess, idx:Int, dflt:Any=null) Source: stdlib.ngs:8279
Get indexed match, returning dflt if the match is not found
glob(pattern:Str, start_dir:Any='.') Source: stdlib.ngs:6308
Work in progress, do not use!
has(container:Any, element:Any)deprecated Source: stdlib.ngs:86
Deprecated in favor of any(container, pattern). Exactly same as "element in container". It's just more convenient in specific cases.

Returns

Bool

Example

[1,2,3].has(2)  # true
[[1,2,3], [1,20,30], [100,200,300]].filter(X.has(1))  # [ [1,2,3], [1,20,30] ]
has_no(container:Any, element:Any)deprecated Source: stdlib.ngs:97
Deprecated in favor of none(container, pattern). Exactly same as "element not in container". It's just more convenient in specific cases.

Returns

Bool

Example

[1,2,3].has_no(2)  # false
[[1,2,3], [1,20,30], [100,200,300]].filter(X.has_no(1))  # [ [100,200,300] ]
hash(x:Any)
Calculate hash value. Same function that Hash uses internally. Currently Fowler-Noll-Vo (FNV) hash function.

Returns

Int - unsigned 32 bit integer

Example

hash(100)  # 100, Numbers are mapped to themselves.
hash("A")  # 84696414
hash("AB")  # 276232888
human_type_name(p:Any)experimental Source: stdlib.ngs:6073
Human readable type name for the Path type and its subtypes. TODO: find better name.
identity(x:Any) Source: stdlib.ngs:776
The identity function.

Returns

x
Ifx(val:Any) Source: stdlib.ngs:8136
Convenience method for creating MustIfx

Returns

MustIfx
in(x:Any, h:Hash)
Check key presence in a Hash

Returns

Bool

Example

"a" in {"a": 1}  # true
"b" in {"a": 1}  # false
in(x:Any, e:Eachable1) Source: stdlib.ngs:1940
Checks whether element x is in Eachable1

Parameters

xNeedle
eHaystack

Returns

Bool

Example

 1 in [1,2,3].Iter()  # true
10 in [1,2,3].Iter()  # false
in(k:Any, hl:HashLike) Source: stdlib.ngs:2231
Check whether k is in the HashLike

Returns

Bool
in(x:Any, s:Set) Source: stdlib.ngs:2418
Check if the value is in the set

Returns

Bool
in(x:Any, arr:Arr) Source: stdlib.ngs:3178
Checks whether element x is in array arr

Parameters

xNeedle
arrHaystack

Returns

Bool

Example

 1 in [1,2,3]  # true
10 in [1,2,3]  # false
index(arr:Arr, pattern:Any=method, start:Int=0, dflt:Any=block) Source: stdlib.ngs:3455
Find index of the first value that matches the pattern. TODO: Make it work on anything with each() method. In future, will throw exception if element is not found and default is not provided. Now returns null for backwards compatibility in this case.

Parameters

arrItems to look at
patternTest function or anything else acceptable by (=~), defaults to Bool.constructors
startIndex to start search at
dfltDefault value. If dflt is a Fun, the result of dflt() is used instead.

Returns

Int or Value(dflt). Temporary also null, for backwards compatibility.

Example

[1,2,11,3,4].index(X>10)  # 2
indexes(e:Eachable1, pattern:Any=method) Source: stdlib.ngs:3476
Find all indexes of values that match the pattern

Parameters

patternTest function or anything else acceptable by (=~), defaults to Bool.constructors

Returns

Arr of Int

Example

[1,5,1,10].indexes(X>2)  # [1,3]
indexes(arr:Arr, r:PredRange, dflt:Any=block) Source: stdlib.ngs:3641
Find the indexes of elements of the given PredRange. Throws IndexNotFound if there is no match between the elements of arr and r and dflt is not given.

Parameters

dfltDefault value. If dflt is a Fun, the result of dflt() is used instead.

Returns

NumRange with .include_start=true and .include_end=false, or Value(dflt)

Example

%[a1 a2 b1 b2 c1].indexes(/^a/../^b/)   # <NumRange 1..2 include_start=true include_end=false step=1>
%[a1 a2 b1 b2 c1].indexes(/^a/.../^b/)  # <NumRange 0..3 include_start=true include_end=false step=1>
init(x:Any) Source: stdlib.ngs:37
No op.

Returns

null
init(rfb:ReturnFromBlock, block:Any, val:Any)internal Source: stdlib.ngs:219
Undocumented
init(e:IndexNotFound, message:Str, container:Any, key:Any) Source: stdlib.ngs:331
IndexNotFound exception constructor

Returns

IndexNotFound object with the given message, container and key fields
init(s:Success, v:Any=null) Source: stdlib.ngs:1016
Initialize Success with the given value.
init(l:Lit, val:Any) Source: stdlib.ngs:1113
Undocumented
init(ms:MatchSuccess, matches:Arr, pattern:Any) Source: stdlib.ngs:1143
Successful match constructor
init(mf:MatchFailure, data:Any, pattern:Any) Source: stdlib.ngs:1146
Unsuccessful constructor
init(mc:MatchContext, root:Any)experimental Source: stdlib.ngs:1159
Undocumented
init(n:Not, pattern:Any) Source: stdlib.ngs:1203
Undocumented
init(pa:PatternAction, pattern:Any, action:Any)experimental Source: stdlib.ngs:1229
Undocumented
init(c:Capture, pattern:Any=method) Source: stdlib.ngs:1261
Make a pattern that captures the matching value. The matched value will be stored in MatchContext.positional

Parameters

patternOptional pattern to match. Defaults to Any.

Example

m = [1,2] =~ Capture([Capture(Int), Capture(Int)])  # m.matches =~ [Arr, 1, 2]
init(c:Capture, name:Str, pattern:Any=method) Source: stdlib.ngs:1271
Make a pattern that captures the matching value. The matched value will be stored in MatchContext.named[name]

Parameters

patternOptional pattern to match. Defaults to Any.

Example

m = {"a": 1, "b": 2} =~ {"a": Capture("arg1"), "b": Capture("arg2")}; m.named.arg1 + m.named.arg2  # 3
m = {"a": 1, "b": 2} =~ {"a": Capture("arg1", Int), "b": Capture("arg2", Str)}  # Doesn't match - b is Int
init(ie:IfExists, pattern:Any) Source: stdlib.ngs:1314
Undocumented
init(b:Branch, pattern:Any) Source: stdlib.ngs:1327
Pattern for trying all possible branches. Always reports positive match.
init(e:Each, pattern:Any) Source: stdlib.ngs:1346
Undocumented
init(t:Transformed, transformation:Fun, pattern:Any) Source: stdlib.ngs:1353
Undocumented
init(r:Repeat, pattern:Any, count:NumRange) Source: stdlib.ngs:1450
Undocumented
init(r:Repeat, pattern:Any, count:Int) Source: stdlib.ngs:1454
Undocumented
init(r:Repeat, pattern:Any) Source: stdlib.ngs:1456
Undocumented
init(ap:AtPath, path_pattern:Any, value_pattern:Any) Source: stdlib.ngs:1501
Undocumented
init(rp:ResetPath, pattern:Any)experimental Source: stdlib.ngs:1557
Undocumented
init(hl:DeprecatedTopLevelHashlike, deprecated_field:Any, h:Hash=null) Source: stdlib.ngs:2374
Create a HashLike.

Parameters

hIf provided, used as initial value.

Example

HashLike(%{a aha b bee}) # <HashLike a=aha b=bee>
init(r:Range, start:Any, end:Any, include_start:Any=true, include_end:Any=false, step:Any=1) Source: stdlib.ngs:2859
Range constructor. Throws InstantiatingAbstractType if r is exactly of type Range (not a sub-type).
init(r:NumRange, start:Any, end:Any, include_start:Any=true, include_end:Any=false, step:Any=1) Source: stdlib.ngs:2899
NumRange constructor. Validates that start and end are Num or Null, step is Num.
init(b:FullBox, val:Any) Source: stdlib.ngs:4518
FullBox constructor. Saves val into .val

Example

# Simplified code from the_one() method:
ret = EmptyBox()
something.each(F(elt) {
	if elt =~ pattern {
		ret throws ElementNotFound("the_one() had more than one match")
	}
	ret = FullBox(elt)
})
not(ret) throws ElementNotFound("the_one() had no matches")
ret.val # Has the value
init(h:Holder, val:Any) Source: stdlib.ngs:4710
Holder constructor
init(t:Thread, name:Str, f:Fun, arg:Any) Source: stdlib.ngs:5626
Creates and runs a thread. The code that the created thread runs is f, which is passed arg.
init(t:Thread, f:Fun, arg:Any) Source: stdlib.ngs:5654
Creates and runs a thread. The code that the created thread runs is f, which is passed arg.
init(ss:SemanticOutput, category:Str, s:Any) Source: stdlib.ngs:5915
Undocumented
init(pr:ProcessRedir, fd:Any, marker:Any, datum:Any) Source: stdlib.ngs:6488
Undocumented
init(pr:ProcessRedir, fd:Any, marker:Any, datum:File) Source: stdlib.ngs:6490
Undocumented
init(r:CommandRedir, fd:Any, marker:Any, datum:Any) Source: stdlib.ngs:6843
Initialize CommandRedir object. Used internally for commands syntax.

Automatically called by NGS for syntax

$(my_prog >my_file)
init(r:CommandRedir, fd:Any, marker:Any, datum:Null) Source: stdlib.ngs:6850
Throw exception whend redirecting to/from null
init(s:SubSeq, val:Any) Source: stdlib.ngs:8127
SubSeq constructor
init(lines:Lines, backtrace:Backtrace, parent_backtrace:Any=null) Source: stdlib.ngs:8744
Convert Backtrace to human-readable format

Example

Lines(bt).echo()
init(rd:ResDef, anchor:Any) Source: autoload/globals/Res.ngs:7
Undocumented
init(i:FilterIter, upstream_iter:Iter, pattern:Any) Source: autoload/globals/Iter.ngs:136
EXPERIMENTAL! Do not use!
init(i:ConstIter, val:Any) Source: autoload/globals/Iter.ngs:227
Constant iterator constructor.

Parameters

valthe constant value to use in next() and peek()
init(ri:RecIter, x:Any) Source: autoload/globals/Iter.ngs:389
Undocumented
init(rd:AWS::SecGroup, Name:Str, VpcId:Any) Source: autoload/globals/AWS.ngs:503
Initialize SecGroup from security group name and vpc.

Example

AWS::SecGroup("https-server", AWS::Vpc(...))
init(p:AWS2::Parameter, res_type:Type, param_name:Str, param_value:Any) Source: autoload/globals/AWS2.ngs:241
Undocumented
init(rd:AWS2::SecGroup, GroupName:Str, VpcId:Any) Source: autoload/globals/AWS2.ngs:623
Initialize SecGroup from security group name and vpc.

Example

AWS2::SecGroup("https-server", AWS2::Vpc(...))
init(t:Table, name:Any=null) Source: autoload/globals/Table.ngs:29
Initialize rows to an empty array
init(t:Table, name:Any, rows_hashes:Arr) Source: autoload/globals/Table.ngs:45
Create named table containing provided rows

Parameters

namename of the table for display and for configuration purposes
rows_hashesrows, each row is a Hash
init(tv:TableView, name:Any=null, view_name:Str=null, columns:Arr=null) Source: autoload/globals/Table2.ngs:9
Undocumented
init(c:_Cell, val:Any) Source: autoload/globals/Table2.ngs:39
Any unknown value is a table cell with one row, Str(val)
init(c:_Cell, val:Any, width:Int) Source: autoload/globals/Table2.ngs:82
Make a cell of given width. Uses _Cell(val).
init(t:Table, name:Any=null) Source: autoload/globals/Table2.ngs:136
Initialize rows to an empty array
init(ctx:TrContext, root:Any, transformation:Any) Source: autoload/globals/tr.ngs:21
Undocumented
init(cmd:TrCommand, x:Any, ctx:TrContext) Source: autoload/globals/tr.ngs:43
Undocumented
init(gnd:GlobalNamespaceDescription, this_version_index:Any)
Undocumented
inspect(path:Arr, val:Any)internal Source: stdlib.ngs:646
Internal method. Please do not use. Inspect any value.

Returns

Arr with exactly one Str of the form <TYPE_NAME ...>
inspect(path:Arr, x:Any)internal Source: stdlib.ngs:709
Internal method. Please do not use. For Type, NativeMethod, UserDefinedMethod

Returns

Arr of Str
inspect(path:Arr, h:Any)internal Source: stdlib.ngs:738
Internal method. Please do not use. Inspect Hash and similar data structures

Returns

Arr of Str
inspect(x:Any) Source: stdlib.ngs:770
Inspect any object

Returns

Human readable representation of the object
instantiate_param_dflt(x:Any) Source: stdlib.ngs:31
Returns deep_copy(x)
Int(s:Str, base:Any=10) Source: stdlib.ngs:5006
Convert to Int. Surrounding whitespace is ignored. Throws InvalidArgument if the number in s is not well-formatted.

Returns

Int

Example

Int(" 100 ")  # 100
intersperse(a:Arr, delim:Any) Source: stdlib.ngs:3912
Insert delimiter element between each two elements in an array

Returns

Arr

Example

[1,2,3].intersperse(0)  # [1,0,2,0,3]
is(obj:Any, t:Type)
Check whether obj is of type t. Uses same function that is used for matching arguments with method parameters when calling a method.

Returns

Bool

Example

1 is Int  # true
[] is Arr  # true
[] is Int  # false
is not(a:Any, b:Any) Source: stdlib.ngs:75
"is not" operator. Exactly same as "not(a is b)".

Example

1    is not Null  # true
null is not Null  # false
last(e:Eachable1, pattern:Any=method, dflt:Any=block) Source: stdlib.ngs:1723
Find last element in e that matches the pattern.

Parameters

patternTest function or anything else acceptable by =~, defaults to Bool.constructors
dfltDefault value. If dflt is a Fun, the result of dflt() is used instead.

Returns

Either the element or Value(dflt) if element was not found.

Example

[1,2,3].last(X>1, 10) == 3
[].last()  # ElementNotFound exception
ll_maybe_wrap(v:Any)
Undocumented
ll_set_global_variable(idx:Int, val:Any)
Do not use directly! Set global variable by index.
map_base_idx(base:Any, n:Int, mapper:Fun)deprecated Source: stdlib.ngs:1885
Deprecated. Map when there is more than one element. If there is exactly one element, it's left as is

Parameters

mapperWill be called with zero based index and successive elements from arr

Returns

Arr
match(val:Any, pattern:Any) Source: stdlib.ngs:9267
Used by match EXPR { ... } construct to check whether the expression matches the case. %AUTO match EXPR { ... }

Returns

val =~ pattern

Example

r = match x {
  Int  "Got integer"
  /^a/ "Got special string"
  Str  "Got regular string"
}
max(a:Any, b:Any, *rest:Arr) Source: stdlib.ngs:3768
Find maximal element under (>)
meta(obj:Any)
Get meta. Meta is auxiliary data slot. It is available on all non-immediate objects. The idea is to store additional information that will not get in your way in cases when you don't care about it.
meta(obj:Any, v:Any)
Set meta. Meta is auxiliary data slot. It is available on all non-immediate objects. The idea is to store additional information that will not get in your way in cases when you don't care about it.
meta(o:Any) Source: stdlib.ngs:474
Wraps native meta() and in case that if there is none, sets it to empty hash.
min(a:Any, b:Any, *rest:Arr) Source: stdlib.ngs:3765
Find minimal element under (<)
none(e:Eachable1, pattern:Any=method) Source: stdlib.ngs:3264
Check whether there is no element in e that satisfies the given pattern. Exactly same as not(any(e, pattern)) .

Parameters

eThe items to check
patternTest function or anything else acceptable by (=~), defaults to Bool.constructors

Returns

Bool

Example

[0,1,2].none(X>2)  # true
[0,1,2].none(X<2)  # false
normalize_presence_list(x:Any) Source: stdlib.ngs:4816
Internal method. Please do not use. Converts Presence or Arr[something] to Arr[Presence]. Used by Res and friends.
not(x:Any) Source: stdlib.ngs:44
Boolean negation for non-boolean values. Converts to boolean first.

Returns

Bool
not in(a:Any, b:Any) Source: stdlib.ngs:67
"not in" operator. Exactly same as "not(a in b)"

Example

10 not in [1,2]  # true
1  not in [1,2]  # false
only(pattern:Any, mapper:Fun)deprecated Source: stdlib.ngs:1618
Deprecated. Use when(val, pat, new_val) instead. Transform mapper to handle only items matching pattern. Non-matching items will be returned as is.

Example

["abc", 1, "def", 2].map(only(Int, X*2))  # ["abc", 2, "def", 4]
only(val:Any, pattern:Any, mapper:Fun)deprecated Source: stdlib.ngs:1628
Same as val.when(pattern, mapper)
partition(something:Eachable1, pattern:Any=method) Source: stdlib.ngs:1681
Partition elements in something according to the pattern into two arrays. First array contains all elements that match the pattern. The second array contains all elements that do not match the pattern.

Parameters

somethingEachable1
patternTest function or anything else acceptable by (=~), defaults to Bool.constructors

Returns

Array with two arrays in it

Example

partition([1,10,2,20], X>=10)  # [[10, 20], [1, 2]]
partitionk(something:Eachable2, pattern:Any=method) Source: stdlib.ngs:4167
Undocumented
partitionv(something:Eachable2, pattern:Any=method) Source: stdlib.ngs:4172
Undocumented
Path(s:Str, subtype:Any=false) Source: stdlib.ngs:6132
Path constructor

Parameters

spath
subtypeReturn Path sub-type, depending on lstat() call

Returns

Path or sub-type of Path

Example

Path(".")  # <Path path=.>
Path(".", true)  # <Dir path=.>
``find tmp/v8``.map(Path(X, true)).map(Type).name.Stats()  # <Stats: {Dir=287, File=9220}>
pfilter(e:Eachable1, pattern:Any) Source: stdlib.ngs:5774
Parallel filter. Typically should be used with "heavy" pattern such as SSH.

Returns

Of same type as e

Example

Set(1..10).pfilter(X>3)  # <Set 4, 5, 6, 7, 8, 9>
pfilter(e:Eachable1, threads:Int, pattern:Any) Source: stdlib.ngs:5785
Parallel filter. Typically should be used with "heavy" pattern such as SSH.

Returns

Of same type as e

Example

Set(1..10).pfilter(2, X>3)  # <Set 4, 5, 6, 7, 8, 9>
Pfx(val:Any) Source: stdlib.ngs:8132
Convenience method for creating MustPfx

Returns

MustPfx
print_exception(e:Exception, level:Int=0, parent:Exception=null, echo:Any=method) Source: stdlib.ngs:8761
Print exception to stderr. Uses inspect().

Parameters

levelindentation level to use (two spaces for each level)
parentparent exception if print_exception() was called for .cause exception
push(arr:Arr, v:Any)
Append item to an array.

Returns

arr

Example

a=[1,2]; a.push(3)  # a is now [1,2,3]
push(al:ArrLike, val:Any) Source: stdlib.ngs:2083
Push an element to the underlying array.
push(s:Set, v:Any) Source: stdlib.ngs:2406
Add an element to the set

Returns

s
push(s:Stats, k:Any) Source: stdlib.ngs:5568
Increment the named counter

Parameters

kthe name of the counter to increment

Example

Stats().push("a").push("a").push("b")["a"]  # 2
push_all(dst:Any, e:Eachable1) Source: stdlib.ngs:1948
Push all elements of e into dst.

Returns

dst
rand(something:Any, n:Int) Source: stdlib.ngs:9062
Pick n elements from something. Uniqueness of picked elements is not guaranteed.

Returns

Any
rand_uniq(something:Any, n:Int) Source: stdlib.ngs:9043
Pick n random unique elements from something

Parameters

somethingSomething that has len(something) and something[idx]

Returns

Arr or Str, depending on something
read(fd:Int, count:Any=null) Source: stdlib.ngs:6505
Read all data from a file referenced by file descriptor without parsing it.

Parameters

fdFile descriptor to read from

Returns

Str

Example

read(0)  # All data from stdin
read(p:Pipe, count:Any=null) Source: stdlib.ngs:6675
Read from Pipe without parsing. TODO: document if it throws.

Returns

read data

Example

data = read(myipe)
read(pp:ProcessesPipeline, count:Any=null) Source: stdlib.ngs:7598
Read from last process of ProcessesPipeline

Example

p = $(seq 3 | tac |);
data = read(p);
p.close()
read(f:MaybeFile, dflt:Any=null) Source: autoload/globals/MaybeFile.ngs:10
Reads the whole file using previously defined read()

Returns

Like read(File) or dflt if the file is not present.
reduce(something:Eachable1, start:Any, f:Fun) Source: stdlib.ngs:1843
Combine items to a single value using the supplied binary function First f is applied to start and the first element of something then on each step f is applied to previous result and next element of something.

Parameters

somethingobject of any type that has each(something, callback) implemented
startFirst argument of f, for the first call of f
fThe combining function

Example

F sum(something) something.reduce(0, (+))
register_column(t:Table, k:Any) Source: autoload/globals/Table.ngs:60
Internal method. Please do not use.
reject(something:Eachable1, pattern:Any=method) Source: stdlib.ngs:1782
Filter something to an Arr (array) of values matching the pattern

Parameters

somethingobject of any type that has each(something, callback) implemented
patternDecision function to be called with each item as first argument. When item matches the pattern, the item will not appear in the resulting array

Returns

Arr

Example

(1...10).reject(F(num) num % 2 == 0)  # Gives [1,3,5,7,9]
(1...10).reject(X<5)  # Gives [5,6,7,8,9,10]
reject(i:Iter, pattern:Any) Source: autoload/globals/Iter.ngs:185
EXPERIMENTAL! Do not use!
rejectk(h:Eachable2, pattern:Any=method) Source: stdlib.ngs:4137
Filter hash by keys, removing matched. See filterk().

Example

{"a1": 1, "a2": 2, "b1": 10}.rejectk(/^b/)  # {"a1": 1, "a2": 2}
rejectv(h:Eachable2, pattern:Any=method) Source: stdlib.ngs:4152
Filter hash by values
replace(dst:Any, src:Any)
DISCOURAGED. Replace one object with another. dst and src must be of the same type.

Example

a = [1,2,3]
a.replace([4,5])
a  # [4,5]
replace(e:Eachable1, src:Any, dst:Any) Source: stdlib.ngs:1828
Replace all occurrences of src with dst TODO: Return same type, not Arr

Returns

Arr

Example

["ssh", "IP", "w"].replace("IP", "10.0.0.100")  # ['ssh','10.0.0.100','w']
replace(f:File, src:Any, dst:Any) Source: stdlib.ngs:6423
Replace in a file. Wrapper around replace(Str, Any, Any).

Returns

f
Result(fun:Fun, catch:Any=method) Source: stdlib.ngs:993
Runs the computation and wraps the result: a value is wrapped in Success and an exception matching catch is wrapped in Failure.

Parameters

catchPattern of exceptions to wrap in Failure; other exceptions propagate. Defaults to Exception.

Returns

Success or Failure

Example

{ fetch("conf.json") }.Result(FileIOFail)  # Failure if the file is unreadable; other errors propagate
retry(times:Int=60, sleep:Any=1, logger:Fun=method, success_predicate:Any=method, title:Any='<retry>', progress_cb:Fun=method, success_cb:Fun=method, fail_cb:Any=method, body:Fun=method) Source: stdlib.ngs:9107
Retry. Executes given "body" "times" times. Throws RetryFail if all calls fail and fail_cb is not provided.

Parameters

timesLimit of times to run "body"
sleepEither sleep in seconds between tries or Iter that returns successive sleep times in seconds
loggerFunction to use to log attempts, caught body exceptions and sleep times. Defaults to stdlib's debug.
success_predicateCANDIDATE FOR REMOVAL. Run against body results to. Says whether the attempt succeeded. Defaults to Bool.
titlePrefix strings sent to logger with this string. Defaults to "<retry>".
progress_cbCalled before each attempt with (1) current attempt number and (2) limit of attempts ("times"). Defaults to do nothing.
success_cbCalled when body succeeds with the result that comes from body. Defaults to identity function.
fail_cbIf passed, called if all attempts fail. Defaults to null.

Returns

Any. Result of success_cb or result of fail_cb.

Example

page = retry(times=10, sleep=ExpBackIter(), body={ try `curl "http://flaky-site.com"` })
retry_assert(val:Any, pattern:Any, msg:Str='Assertion failed')experimental Source: stdlib.ngs:9164
Similar to assert(). Caught and ignored by nearest retry() on all but last retry.
retry_assert(val:Any, msg:Str='Assertion failed')experimental Source: stdlib.ngs:9173
Similar to assert(). Caught and ignored by nearest retry() on all but last retry.
return(b:Block, val:Any=null)internal Source: stdlib.ngs:247
Undocumented

Automatically called by NGS for syntax

block NAME { NAME.return() }
return(mc:MatchContext, x:Any)deprecated Source: stdlib.ngs:1192
Undocumented
run(dv:DynVar, val:Any, body:Fun) Source: stdlib.ngs:5846
Run body with dv bound to val.

Returns

Whatever body call returns

Example

dv = DynVar(); dv.run(1, { dv.get() })  # 1
run(r:AWS::Res, log_pfx:Str, cp:CommandsPipeline, do_decode:Any=true)internal Source: autoload/globals/AWS.ngs:118
Run a command. Internal method. Please do not use outside the AWS library.
run(rd:AWS::ResDef, log_pfx:Str, cp:CommandsPipeline, do_decode:Any=true)internal Source: autoload/globals/AWS.ngs:185
Run an external command related to the resource definition. Will not run the command if rd.dry_run is true.

Parameters

do_decodeWhether to decode the output

Returns

Either parsed output or finished CommandsPipeline (processes in CommandsPipeline finished)
run(r:AWS2::Res, log_pfx:Str, cp:CommandsPipeline, do_decode:Any=true)internal Source: autoload/globals/AWS2.ngs:141
Run a command. Internal method. Please do not use outside the AWS library.
run(rd:AWS2::ResDef, log_pfx:Str, cp:CommandsPipeline, do_decode:Any=true)internal Source: autoload/globals/AWS2.ngs:203
Run an external command related to the resource definition. Will not run the command if rd.dry_run is true.

Parameters

do_decodeWhether to decode the output

Returns

Either parsed output or finished CommandsPipeline (processes in CommandsPipeline finished)
SafeStr(val:Any)experimental Source: stdlib.ngs:8735
Don't use, subject to change, including name
set(obj:Any, field:Str, val:Any) Source: stdlib.ngs:853
Sets the given field to the given value

Returns

The modified obj

Example

s.len() != 1 throws InvalidArgument("ord() argument must be of length 1 exactly").set('given', s)
# Would else be written as
if s.len() != 1 {
	e = InvalidArgument("ord() argument must be of length 1 exactly")
	e.given = s
	throw e
}
set(obj:Any, **kwargs:Hash) Source: stdlib.ngs:861
Sets the given fields to the given values

Returns

The modified obj

Example

my_cond throws InvalidArgument("Out of range").set(min=0, max=10, given=12)
set_last_path_element(mc:MatchContext, x:Any) Source: stdlib.ngs:1186
Undocumented
Sfx(val:Any) Source: stdlib.ngs:8140
Convenience method for creating MustSfx

Returns

MustSfx
shift(arr:Arr, dflt:Any)
Get the first element and remove it from the array. Returns dflt if there are no elements in the array.

Returns

Any
shift(h:Hash, k:Any) Source: stdlib.ngs:4451
Get the given key from a Hash and remove it from the Hash. Underlying h[k] may throw KeyNotFound.

Example

h = {"a": 1}
s = h.shift("a")  # h == {} and s == 1
shift(h:Hash, k:Any, dflt:Any) Source: stdlib.ngs:4459
Get a key from a Hash and remove it from the Hash. If the key is not in the Hash, return Value(dflt, k)

Parameters

dfltDefault value. If dflt is a Fun, the result of dflt(k) is used instead.

Example

h = {}
h.shift("a", 7)  # 7
skip(i:Iter, pattern:Any=method) Source: autoload/globals/Iter.ngs:443
Returns the given Iter but skipping leading elements while the pattern matches. If all elements match the pattern, the Iter will be empty. Default pattern skips leading truthy elements (stops at first falsy).

Returns

Iter

Example

[1, 2, null, 3].Iter().skip().Arr() == [null, 3]
[0, 2, 3, 25, 19, 7].Iter().skip(X != 3).Arr() == [3, 25, 19, 7]
split(e:Eachable1, delim:Any) Source: stdlib.ngs:3875
Split e into arrays

Returns

Arr of Arr

Example

[1, "a", 2, 3, "a", 4].split("a")  # [[1], [2, 3], [4]]
store(filename:Str, data:Any, encode_hints:Hash={}) Source: stdlib.ngs:6825
encode() and write() the data to the file

Returns

null (but subject to change)
store(file:File, data:Any, encode_hints:Hash={}) Source: stdlib.ngs:6832
encode() and write() the data to the file
store_to(data:Any, target:Any, encode_hints:Hash={}) Source: stdlib.ngs:6835
Same as store(target, data, encode_hints)
Str(x:Any, target_width:Int, ch:Str=' ') Source: stdlib.ngs:5263
Convert anything to Str of a given width
StrForTable(x:Any) Source: autoload/globals/Table.ngs:9
Internal method. Please do not use.
StrForTable(x:Any, width:Int) Source: autoload/globals/Table.ngs:12
Internal method. Please do not use.
take(something:Eachable1, pattern:Any)experimental Source: stdlib.ngs:1794
EXPERIMENTAL! Do not use!

Example

[1,2,3,1,2].take(X<3)  # [1,2]
tap(val:Any, cb:Fun) Source: stdlib.ngs:1894
Call cb with val

Returns

val

Example

long_computation_part1().tap(F(x) echo("DEBUG: $x")).long_computation_part2()
the_one(e:Eachable1, pattern:Any=method, body:Fun=method, found_more:Any=block, found_none:Any=block) Source: stdlib.ngs:1747
Find the only element that matches the pattern and execute given code with the value

Parameters

bodyThe code to execute when exactly one element that matches the pattern was found. Executed with the found value. It's value will be returned as result of the_one().
found_moreThe value to return when more than one element matches the pattern. If found_more is a Fun, the result of found_more() is returned instead. Defaults to throwing ElementNotFound.
found_noneThe value to return when none of the elements match the pattern. If found_none is a Fun, the result of found_none() is returned instead. Defaults to throwing ElementNotFound.

Returns

One of the following: body(the_element), Value(found_more), Value(found_none)

Example

F name(dn:MethodDocNode) {
	dn.children.the_one(MethodNameDocNode).text[0]
}
tr(x:Any, pattern:Any, tc:TrContext) Source: autoload/globals/tr.ngs:107
Checks whether x matches the pattern

Returns

Lit(x) or TrNoMatch()
tr(x:Any, a:Arr, tc:TrContext) Source: autoload/globals/tr.ngs:114
Match / transform x using the pattern in a

Returns

Lit or TrCommand
tr(x:Any, h:Hash, tc:TrContext) Source: autoload/globals/tr.ngs:138
Match / transform x using the pattern in h.

Parameters

xHash or HashLike

Returns

Lit or TrCommand
tr(x:Any, a:AnyOf, tc:TrContext) Source: autoload/globals/tr.ngs:158
Match / transform x using the pattern in a. First match shortcuts the evaluation: further items in a are not tried.

Returns

Lit or TrNoMatch
tr(x:Any, pa:PatternAction, tc:TrContext) Source: autoload/globals/tr.ngs:176
Transform x using pa::action of x matches pa::pattern. pa::action will be called with (Any, TrContext). pa::action can either return new data or perform an operation using TrContext. Currently supported operation is skip(TrContext).

Returns

Lit, TrCommand, or TrNoMatch
tr(x:Any, transformation:Any) Source: autoload/globals/tr.ngs:190
Public API of the transformation/tr() experimental facility

Example

cat fhir_questionnaire_01.json | ngs -ppj '_.tr({"url": AnyOf("http://hl7.org/fhir/StructureDefinition/maxValue", "http://hl7.org/fhir/StructureDefinition/minValue")} -> skip(Y)).tr([] -> skip(Y))' >fhir_questionnaire_01.clean.json
Type(name:Str, doc:Any, ns:Any)
Create a new type. Do not use directly.

Automatically called by NGS for syntax

type MyType
Type(x:Any)
Returns type of the given object

Parameters

xObject. Currently only objects of NormalType are supported.
Type(t:Str, doc:Any, ns:Any, parent:Type) Source: stdlib.ngs:111
Create a new type. Do not use directly.

Automatically called by NGS for syntax

type MyType2(MyType1)
Type(t:Str, doc:Any, ns:Any, parents:Arr) Source: stdlib.ngs:116
Create a new type. Do not use directly.

Automatically called by NGS for syntax

type MyType2([MyParent1, MyParent2, ...])
typeof(x:Any)deprecated Source: stdlib.ngs:2723
Use Type(x)

Returns

Type
unshift(arr:Arr, elt:Any) Source: stdlib.ngs:3521
Prepend one element to the given array

Returns

Modified arr

Example

x=[1,2]
x.unshift(3)
echo(x)  # Outputs: [3,1,2]
validate(val:Any, param:Str, pattern:Any) Source: stdlib.ngs:396
Throws InvalidArgument naming the parameter if val does not match the pattern. Use for checking arguments.

Parameters

valArgument value to check
paramName of the parameter
patternPattern val must match

Returns

val

Example

validate(-5, 'x', Int)  # InvalidArgument: Invalid argument 'x', got -5, expected Int
validate(-5, 'x', { A > 0 })  # InvalidArgument: Invalid argument 'x', got -5, expected to pass the check at my.ngs:10
Value(x:Any, *args:Arr) Source: stdlib.ngs:835
Used for converting default values or functions to values

Returns

x
when(val:Any, pat:Any, new_val:Any) Source: stdlib.ngs:1640
If val matches pat, return new_val.Value(val); otherwise return val. Use instead of older only()

Example

"abcd".mapo(X.when("b", "*"))  # a*cd
"abcd".mapo(F(x) x.when("b", "[$X]"))  # a[b]cd
without(e:Eachable1, without_elt:Any)deprecated Source: stdlib.ngs:3377
Filter out all occurrences of specific value Deprecated. Use reject().

Parameters

eitems to filter
without_eltThe value to filter out

Returns

Arr

Example

[1,2,3,2].without(2)  # [1,3]
without(e:Eachable2, without_k:Any)deprecated Source: stdlib.ngs:4341
Filter out specific key. Deprecated. Use rejectk() or fields(Not(...)).

Parameters

eSource
without_kThe key to filter out

Example

{'a': 1, 'b': 2, 'c': 3}.without('a')  # {'b': 2, 'c': 3}
without(e:Eachable2, without_k:Any, without_v:Any)deprecated Source: stdlib.ngs:4353
Filter out specific key-value pair. Deprecated. Use reject().

Parameters

eSource
without_kThe key to filter out
without_vThe value to filter out

Example

{'a': 1, 'b': 2, 'c': 3}.without('a', 1).without('b', 22)  # {'b': 2, 'c': 3}
without(ds:ArrLike, without_elt:Any) Source: autoload/globals/DelimStr.ngs:25
Get new DelimStr without the given element

Example

DelimStr("/bin:/usr/bin:/usr/local/bin").without("/usr/bin").Str()  # "/bin:/usr/local/bin"
write_to(data:Any, target:Any) Source: stdlib.ngs:9321
Same as write(target, data)
~(x:Any, a:AnyOf) Source: stdlib.ngs:2127
Checks whether x matches (~) any of the alternatives.
AWS::add_to_known_hosts(r:AWS::InstanceRes, ip_or_hostname:Any)experimental Source: autoload/globals/AWS.ngs:991
Declarative primitive for adding ssh host fingerprints of AWS Instance resource to known hosts.
AWS::pollute(do_warn:Any=true) Source: autoload/globals/AWS.ngs:1553
Undocumented
AWS::util::world_open_ip_proto(proto:Any) Source: autoload/globals/AWS.ngs:1516
Undocumented
AWS2::add_to_known_hosts(r:AWS2::InstanceRes, ip_or_hostname:Any)experimental Source: autoload/globals/AWS2.ngs:1088
Declarative primitive for adding ssh host fingerprints of AWS Instance resource to known hosts.
AWS2::pollute(do_warn:Any=true) Source: autoload/globals/AWS2.ngs:1855
Undocumented
Doc::transform(p:Doc::Part, transformer:Any) Source: autoload/globals/Doc.ngs:100
Undocumented
Doc::transform(dps:Arr, transformer:Any) Source: autoload/globals/Doc.ngs:105
Undocumented