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:1384
Inequality operator

Example

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

Example

h1 = {"a": 1}
h2 = {"a": 1}
h1 !== h2  # true, same as not(h1===h2)
h1 == h2   # true
%(x:Any, cb:Fun) Source: stdlib.ngs:609
Each operator. Same as calling x.each(cb)

Example

[1,2,3,4] % echo
+?(a:Any, b:Any) Source: stdlib.ngs:621
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}")
.(hl:HashLike, k:Any) Source: stdlib.ngs:786
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:1303
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:1317
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:1309
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:1327
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
.=(hl:HashLike, k:Any, v:Any) Source: stdlib.ngs:791
Set value.

Automatically called by NGS for syntax

your_hashlike.literal_key = v

Returns

v
.=(h:Hash, field:Str, v:Any) Source: stdlib.ngs:1546
Set hash key.

Returns

v

Example

h = {"a": 1}
h.a = 2  # 2, Same as h["a"] = 2
.=(a:Arr, field:Str, v:Any) Source: stdlib.ngs:1588
Set field of every element in array to v

Returns

v

Example

a=[{"x": 1}, {"x": 2}]
a.y = 10
# a == [{"x": 1, "y": 10}, {"x": 2, "y": 10}]
.=(p:Process, field:Str, v:Any) Source: stdlib.ngs:4671
Set process "stdout"

Parameters

field"stdout"

Returns

Unspecified, do not count on this value
.=(p:Process, field:Str, v:Any) Source: stdlib.ngs:4687
Set process "stderr"

Parameters

field"stderr"

Returns

Unspecified, do not count on this value
/(x:Any, mapper:Fun) Source: stdlib.ngs:604
Map operator. Same as calling x.map(mapper)

Example

[1,2,3,4] / F(x) x * 10
::(nti:NormalTypeInstance, k:Any) Source: stdlib.ngs:103
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:108
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(...)
::=(nti:NormalTypeInstance, k:Any, v:Any) Source: stdlib.ngs:111
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:113
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:Null, b:Any) Source: stdlib.ngs:1493
Compare to null

Returns

false
==(a:Any, b:Null) Source: stdlib.ngs:1497
Compare to null

Returns

false
===(a:Any, b:Any)
Sameness comparison.
?(x:Any, predicate:Fun) Source: stdlib.ngs:599
Filter operator. Same as calling x.filter(predicate)

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:777
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:721
Get element from the underlying array.
[]=(hl:HashLike, k:Any, v:Any) Source: stdlib.ngs:781
Set value.

Automatically called by NGS for syntax

your_hashlike[k] = v
[]=(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) Source: stdlib.ngs:614
Call operator. Same as calling f(x)

Example

[1,2,3,4] \ echo
all(e:Eachable, predicate:Any) Source: stdlib.ngs:1702
Check whether all elements in arr satisfy the given predicate.

Parameters

eThe items to check
predicateTest function

Returns

Bool

Example

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

Parameters

eThe items to check
predicateTest function

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/ArgvMatcher.ngs:30
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(condition:Any, *args:Arr) Source: stdlib.ngs:90
Throws AssertFail if condition, after conversion to Bool is false. Same as super(Bool(condition), *args) .

Parameters

conditionnot Bool

Returns

Unspecified, do not count on this value

Example

assert(my_array, "my_array must have elements at this point")
assert_array(actual:Any, title:Str=null) Source: autoload/test.ngs:110
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/test.ngs:44
A helper used by other assert_* methods. Please do not use directly.
assert_bool(actual:Any, title:Str=null) Source: autoload/test.ngs:88
Assert actual is a Bool. Throws TestFail.

Returns

actual
assert_eq(actual:Any, expected:Any, title:Str=null) Source: autoload/test.ngs:59
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/test.ngs:213
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/test.ngs:100
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/test.ngs:132
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/test.ngs:148
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/test.ngs:69
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/test.ngs:79
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/test.ngs:164
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/test.ngs:235
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/test.ngs:223
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/test.ngs:120
Assert actual is a string. Throws TestFail.

Returns

actual
attempt(x:Any, *cbs:Arr) Source: stdlib.ngs:5582
EXPERIMENTAL! Do not use!
attrs(obj:Any)
Get attributes. Attributes 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.
attrs(obj:Any, v:Any)
Set attributes. Attributes 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.
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_debug(s:Any) Source: bootstrap.ngs:69
Undocumented
Box(x:Any) Source: stdlib.ngs:2915
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(a:Arr, idx:Any) Source: stdlib.ngs:2944
Convert array value indexed by the given index

Parameters

idxkey to look in hash

Returns

Box. FullBox if the array has the element indexed by idx, EmptyBox otherwise.

Example

my_array = [10, 20]
my_array.Box(1).map(X*2).each(echo)
# output: 40
my_array.Box(5).map(X*2).each(echo)
# no output
Box(h:Hash, k:Any) Source: stdlib.ngs:2962
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]
}
call(r:Return, v:Any=null) Source: stdlib.ngs:127
Implements calling of Return type instances like the finish(i) call in the example below

Example

F first(r:NumRange, predicate:Fun) {
	finish = Return()
	r.each(F(i) {
		predicate(i) throws finish(i)
	})
	null
}
cell_display_width(x:Any) Source: autoload/Table.ngs:23
Calculate cell display width - any Str()-able object
config(k:Str, v:Any) Source: stdlib.ngs:5511
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, predicate:Any) Source: stdlib.ngs:1863
Count number of items that satisfy the predicate.

Parameters

eItems to look at
predicateTest function

Returns

Int

Example

[1,2,3,11,12].count(X>10)  # 2
count(e:Eachable2, predicate:Any) Source: stdlib.ngs:2603
Count number of key-value pairs in Hash that satisfy the predicate.

Parameters

eSomething to check, typically a Hash
predicateTest function to be called with one key and one value at a time

Returns

Int

Example

{'a': 1, 'b': 2, 'c': 11}.count(F(k, v) v>10)  # 1
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}
dflt(i:NormalTypeInstance, k:Any, v:Any) Source: stdlib.ngs:1052
Set object field if it's not already set

Returns

Field value, the already-existed or new.

Example

my_something.dflt(k, []).push(elt)
dflt(e:Eachable1, k:Any, v:Any) Source: stdlib.ngs:1066
Set a field on all elements if it's not already set

Parameters

eEachable1 with elements of type NormalTypeInstance or Hash

Returns

e

Example

my_items.dflt("source", "(unknown)")
dflt(hl:HashLike, k:Any, v:Any) Source: stdlib.ngs:1093
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:2756
Set a key in a Hash if it's not already set

Returns

Hash value, the already-existed or new.

Example

my_hash.dflt(k, []).push(elt)
dflt(fb:FullBox, x:Any) Source: stdlib.ngs:2975
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:2986
Wrap x in a Box

Returns

FullBox with the 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:4035
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:4243
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:4251
List directory contents and call cb with Path() of each found item. Warning: "." and ".." are included.

Returns

unspecified at this time, do not count on it

Example

's=Stats(); dir("tmp/v8", {s.push(A.typeof().name)}, true); s  # <Stats: {File=23, Dir=16}>'
drop(e:Eachable1, predicate:Any)experimental Source: stdlib.ngs:506
EXPERIMENTAL! Do not use! Filters out items that satisfy predicate at the begginning 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.
echo(x:Any) Source: stdlib.ngs:2243
Echo non-string. Converts x to string first, using Str()

Parameters

xAnything but Str

Returns

null

Example

echo(1)
encode(data:Any, hints:Hash={}) Source: stdlib.ngs:5323
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 }
ensure(x:Any, t:Type)experimental Source: stdlib.ngs:667
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) Source: stdlib.ngs:2365
Optionally, wrap x in an array. Return x if it's already Arr.

Returns

Arr

Example

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

Parameters

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

Parameters

statusconverted to exit code using ExitCode()
ExitCode(x:Any) Source: bootstrap.ngs:42
Undocumented

Returns

always 0
filter(e:Eachable1, predicate:Any) Source: stdlib.ngs:324
Filter e using predicate.

Parameters

eEachable1. WARNING: instances of same type as e must have empty constructor and push() method.
predicateDecision function to be called with each item as first argument. When predicate(item) 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], predicate called as predicate(item, 5)
filter(something:Eachable1, field:Str, predicate:Any)deprecated Source: stdlib.ngs:339
DEPRECATED! Do not use! Use something.filter({field: predicate}) instead.
filter(h:Hash, predicate:Any) Source: stdlib.ngs:2558
Filter hash. Build new hash with kev-value pairs selected by predicate.

Parameters

hSource hash
predicateTest function to be called with one key and one value at a time

Example

{'a': 1, 'b': 2}.filter(F(k, v) k == 'a')  # {'a': 1}
filter(fb:FullBox, predicate:Any) Source: stdlib.ngs:2885
Conditionaly convert FullBox to EmptyBox.

Parameters

predicateTest function to be called with the value in the FullBox

Returns

Box. fb if predicate succeeds, EmptyBox if not.

Example

Box(10).filter(X>5)   # <FullBox val=10>
Box(10).filter(X>20)  # <EmptyBox>
filter(eb:EmptyBox, predicate:Any) Source: stdlib.ngs:2893
Do nothing

Returns

eb

Example

EmptyBox().filter(X>20)  # <EmptyBox>
filter(s:Success, predicate:Any) Source: stdlib.ngs:3090
Run predicate on wrapped value.

Returns

s or Failure

Example

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

Returns

f

Example

Failure("blah").filter(X>5)  # <Failure val=blah>
filter(ds:DelimStr, predicate:Any) Source: autoload/DelimStr.ngs:21
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, predicate:Any) Source: stdlib.ngs:2573
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}
filterv(h:Eachable2, predicate:Any) Source: stdlib.ngs:2586
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:4786
Undocumented
first(e:Eachable1, predicate:Any, default:Any) Source: stdlib.ngs:368
Find first element in e that satisfies the predicate.

Returns

Either the element or the provided default 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
first(e:Eachable1, predicate:Any) Source: stdlib.ngs:384
Find first element in e that satisfies the predicate. Throws ElementNotFound exception if no such element is found.

Returns

The element.

Example

(10..20).first(F(x) x % 3 == 0)  # 12 - first item divisible by 3
(10..20).first(F(x) x % 50 == 0) # ElementNotFound exception
get(arr:Arr, idx:Int, dflt:Any)
Get element at the given index or return dflt if the index is out of range (element at the given index does not exist)

Returns

Any

Example

[1,2,3].get(0, 10)  # 1
[1,2,3].get(5, 10)  # 10
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(al:ArrLike, idx:Int, dflt:Any) Source: stdlib.ngs:724
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:795
Get value by key or dflt if it does not exist

Returns

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

Returns

Any
get(h:Hash, k:Any) Source: stdlib.ngs:1552
Get hash value by key or null if it does not exist

Example

h = {"a": 1}
h.get("a")  # 1
h.get("b")  # null
get(e:Eachable1, field:Str, dflt:Any) Source: stdlib.ngs:1608
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(fb:FullBox, dflt:Any=null) Source: stdlib.ngs:2898
Get FullBox value

Returns

Any

Example

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

Returns

dflt
get(s:Success, dflt:Any) Source: stdlib.ngs:3055
Gets wrapped value

Returns

Any

Example

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

Example

{ 1 / 0 }.Result().get(100)  # 100
glob(pattern:Str, start_dir:Any='.') Source: stdlib.ngs:4284
Work in progress, do not use!
has(container:Any, element:Any) Source: stdlib.ngs:1421
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] ]
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
identity(x:Any) Source: stdlib.ngs:196
The identity function. Simply returns the given parameter.

Returns

The given argument
Ifx(val:Any) Source: stdlib.ngs:5601
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:632
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:768
Check whether k is in the HashLike

Returns

Bool
in(x:Any, arr:Arr) Source: stdlib.ngs:1634
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
in(x:Any, s:Set) Source: autoload/Set.ngs:36
Check if the value is in the set

Returns

Bool
index(arr:Arr, predicate:Any, start:Int=0, dflt:Any=[]) Source: stdlib.ngs:1919
Find index of first value that satisfies the predicate. 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 compatibilty in this case.

Parameters

arrItems to look at
predicateTest function
startIndex to start search at
dfltdefault value to return when element is not found

Returns

Int or dflt. Temporary also null, for backwards compatibilty.

Example

[1,2,11,3,4].index(X>10)  # 2
indexes(e:Eachable1, predicate:Any) Source: stdlib.ngs:1936
Find all indexes of values that satisfy the predicate

Parameters

predicateTest function

Returns

Arr of Int

Example

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

Returns

NumRange with .include_start=true and .include_end=false

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(e:IndexNotFound, message:Str, container:Any, key:Any) Source: stdlib.ngs:68
IndexNotFound exception constructor

Returns

IndexNotFound object with the given message, container and key fields
init(r:Range, start:Any, end:Any, include_start:Any=true, include_end:Any=false, step:Any=1) Source: stdlib.ngs:1295
Range constructor. Throws InstantiatingAbstractType if r is exactly of type Range (not a sub-type).
init(b:FullBox, val:Any) Source: stdlib.ngs:2837
FullBox constructor. Saves val into .val

Example

# Simplified code from the_one() method:
ret = EmptyBox()
something.each(F(elt) {
	if predicate(elt) {
		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(s:Success, v:Any) Source: stdlib.ngs:3036
Initialize Success with the given value.
init(t:Thread, name:Str, f:Fun, arg:Any) Source: stdlib.ngs:3831
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:3852
Creates and runs a thread. The code that the created thread runs is f, which is passed arg.
init(pr:ProcessRedir, fd:Any, marker:Any, datum:Any) Source: stdlib.ngs:4333
Undocumented
init(r:CommandRedir, fd:Any, marker:Any, datum:Any) Source: stdlib.ngs:4640
Initialize CommandRedir object. Used internally for commands syntax.

Automatically called by NGS for syntax

$(my_prog >my_file)
init(mf:MatchFailure, data:Any, pattern:Any) Source: stdlib.ngs:5554
Unsuccessful construtcor
init(s:SubSeq, val:Any) Source: stdlib.ngs:5592
SubSec construcor
init(lines:Lines, backtrace:Backtrace, parent_backtrace:Any=null) Source: stdlib.ngs:6089
Convert Backtrace to human-readable format

Example

Lines(bt).echo()
init(rd:ResDef, anchor:Any) Source: autoload/Res.ngs:8
Undocumented
init(i:FilterIter, upstream_iter:Iter, predicate:Any, invert_predicate:Bool=false) Source: autoload/Iter.ngs:129
EXPERIMENTAL! Do not use!
init(i:ConstIter, val:Any) Source: autoload/Iter.ngs:225
Constant iterator constructor.

Parameters

valthe constant value to use in next() and peek()
init(rd:AWS::SecGroup, Name:Str, VpcId:Any) Source: autoload/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/AWS2.ngs:227
Undocumented
init(rd:AWS2::SecGroup, GroupName:Str, VpcId:Any) Source: autoload/AWS2.ngs:607
Initialize SecGroup from security group name and vpc.

Example

AWS::SecGroup("https-server", AWS::Vpc(...))
init(t:Table, name:Any=null) Source: autoload/Table.ngs:33
Initialize rows to an empty array
init(t:Table, name:Any, rows_hashes:Arr) Source: autoload/Table.ngs:47
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(gnd:GlobalNamespaceDescription, this_version_index:Any)
Undocumented
inspect(val:Any) Source: stdlib.ngs:5994
Inspect any value.

Returns

Lines with exactly one line
inspect(n:Doc::Node, levels:Any=2) Source: autoload/Doc.ngs:158
Inspect document node

Returns

Lines
intersperse(a:Arr, delim:Any) Source: stdlib.ngs:2350
%EX [1,2,3].intersperse(0) # [1,0,2,0,3]

Returns

Arr
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:1411
"is not" operator. Exactly same as "not(a is b)".

Example

1    is not Null  # true
null is not Null  # false
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:581
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(a:Any, b:Any) Source: stdlib.ngs:6469
Used by match EXPR { ... } construct to check whether the expression matches the case. %AUTO match EXPR { ... }

Returns

Pred(b)(a)

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:2197
Find maximal element under (>)
min(a:Any, b:Any, *rest:Arr) Source: stdlib.ngs:2194
Find minimal element under (<)
normalize_presence_list(x:Any) Source: stdlib.ngs:3139
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:1380
Boolean negation for non-boolean values. Converts to boolean first.

Returns

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

Example

10 not in [1,2]  # true
1  not in [1,2]  # false
only(predicate:Any, mapper:Fun) Source: stdlib.ngs:304
Transform mapper to handle only items matching predicate. Non-matching items will be returned as is.

Example

["abc", 1, "def", 2].map(only(Int, X*2))  # ["abc", 2, "def", 4]
partition(something:Eachable1, predicate:Any) Source: stdlib.ngs:350
Partition elements in something according to the predicate into two arrays. First array contains all elements for which predicate(elt) is true and the second array contains all elements for which predicate(elt) is false.

Parameters

somethingEachable1

Returns

Array with two arrays in it

Example

partition([1,10,2,20], X>=10)  # [[10, 20], [1, 2]]
Path(s:Str, subtype:Any=false) Source: stdlib.ngs:4127
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(typeof).name.Stats()  # <Stats: {Dir=287, File=9220}>
Pfx(val:Any) Source: stdlib.ngs:5597
Convenience method for creating MustPfx

Returns

MustPfx
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:738
Push an element to the underlying array.
push(s:Stats, k:Any) Source: stdlib.ngs:3784
Increment the named counter

Parameters

kthe name of the counter to increment

Example

Stats().push("a").push("a").push("b")["a"]  # 2
push(s:Set, v:Any) Source: autoload/Set.ngs:19
Add an element to the set

Returns

s
push_all(dst:Any, e:Eachable1) Source: stdlib.ngs:640
Push all elements of e into dst.

Returns

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

Returns

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

Returns

Arr
read(fd:Int, count:Any=null) Source: stdlib.ngs:4355
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:4490
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:5208
Read from last process of ProcessesPipeline

Example

p = $(seq 3 | tac |);
data = read(p);
p.close()
reduce(something:Eachable1, start:Any, f:Fun) Source: stdlib.ngs:538
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/Table.ngs:62
Internal method. Please do not use.
reject(something:Eachable, predicate:Any) Source: stdlib.ngs:478
Filter something to an Arr (array) of values using predicate

Parameters

somethingobject of any type that has each(something, callback) implemented
predicateDecision function to be called with each item as first argument. When predicate(item) returns true, 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], predicate called as predicate(item, 5)
rejectk(h:Eachable2, predicate:Any) Source: stdlib.ngs:2579
Filter hash by keys, removing matched. See filterk().

Example

{"a1": 1, "a2": 2, "b1": 10}.rejectk(/^b/)  # {"a1": 1, "a2": 2}
rejectv(h:Eachable2, predicate:Any) Source: stdlib.ngs:2592
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(something:Eachable1, src:Any, dst:Any) Source: stdlib.ngs:525
Replace all occurrences of src with dst TODO: Return same type, not Arr

Parameters

somethingobject of any type that has each(something, callback) implemented

Returns

Arr

Example

["ssh", "IP", "w"].replace("IP", "10.0.0.100")  # ['ssh','10.0.0.100','w']
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:6357
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"` })
run(r:AWS::Res, log_pfx:Str, cp:CommandsPipeline, do_decode:Any=true)internal Source: autoload/AWS.ngs:120
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/AWS.ngs:190
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/AWS2.ngs:129
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/AWS2.ngs:194
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:5982
Don't use, subject to change, including name
set(obj:Any, field:Str, val:Any) Source: stdlib.ngs:228
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:236
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)
Sfx(val:Any) Source: stdlib.ngs:5605
Convenience method for creating MustSfx

Returns

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

Returns

Any
shift(h:Hash, k:Any) Source: stdlib.ngs:2778
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:2788
Get a key from a Hash and remove it from the Hash. If they key is not in the Hash, return dflt

Example

h = {}
h.shift("a", 7)  # 7
split(e:Eachable1, delim:Any) Source: stdlib.ngs:2313
Split e into arrays

Returns

Arr of Arr

Example

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

Returns

null (but subject to change)
Str(x:Any, target_width:Int, ch:Str=' ') Source: stdlib.ngs:3500
Convert anything to Str of a given width
StrForTable(x:Any) Source: autoload/Table.ngs:11
Internal method. Please do not use.
StrForTable(x:Any, width:Int) Source: autoload/Table.ngs:14
Internal method. Please do not use.
take(something:Eachable1, predicate:Any)experimental Source: stdlib.ngs:487
EXPERIMENTAL! Do not use!

Example

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

Returns

val

Example

long_computation_part1().tap(F(x) echo("DEBUG: $x")).long_computation_part2()
the_one(e:Eachable1, predicate:Any) Source: stdlib.ngs:405
Find the only element that satisfies the predicate. Throws ElementNotFound exception if there are no elements that satisfy the predicate or if there is more than one element that satisfies the predicate.

Returns

The only element that satisfies the predicate.
the_one(e:Eachable1, predicate:Any, body:Fun, found_more:Fun=method, found_none:Fun=method) Source: stdlib.ngs:430
Find the only element that satisfies the predicate and execute given code with the value

Parameters

bodyThe code to execute when exactly one element that satisfies the predicate was found. Executed with the found value. It's value will be returned as result of the_one().
found_moreThe code to execute when more than one element satisfies the predicate. It's value will be returned as result of the_one(). Defaults to function returning null.
found_noneThe code to execute when none of the elements satisfy the predicate. It's value will be returned as result of the_one(). Defaults to function returning null.

Returns

Result of running on of the following: body, found_more, found_none

Example

F name(dn:MethodDocNode) {
	dn.children.the_one(MethodNameDocNode).text[0]
}
to_exit_code(x:Any)deprecated Source: stdlib.ngs:15
Deprecated. Use ExitCode.
Type(name:Str, doc:Any, ns:Any)
Create a new type. Do not use directly.

Automatically called by NGS for syntax

type MyType
Type(t:Str, doc:Any, ns:Any, parent:Type) Source: stdlib.ngs:939
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:944
Create a new type. Do not use directly.

Automatically called by NGS for syntax

type MyType2([MyParent1, MyParent2, ...])
typeof(x:Any)
Returns type of the given object

Parameters

xObject. Currently only objects of NormalType are supported.
unshift(arr:Arr, elt:Any) Source: stdlib.ngs:1972
Prepend one element to the given array

Returns

Modified arr

Example

x=[1,2]
x.unshift(3)
echo(x)  # Outputs: [3,1,2]
without(e:Eachable1, without_elt:Any) Source: stdlib.ngs:1837
Filter out all occurrences of specific value

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) Source: stdlib.ngs:2686
Filter out specific key

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) Source: stdlib.ngs:2696
Filter out specific key-value pair

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/DelimStr.ngs:27
Get new DelimStr without the given element

Example

DelimStr("/bin:/usr/bin:/usr/local/bin").without("/usr/bin").Str()  # "/bin:/usr/local/bin"
~(something:Any, pred:Any)deprecated Source: stdlib.ngs:954
EXPERIMENTAL! Do not use! Especially don't count on returned value beyond obvios Bool(x) behaviour. Match anything.
AWS::add_to_known_hosts(r:AWS::InstanceRes, ip_or_hostname:Any)experimental Source: autoload/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/AWS.ngs:1556
Undocumented
AWS::util::world_open_ip_proto(proto:Any) Source: autoload/AWS.ngs:1516
Undocumented
AWS2::add_to_known_hosts(r:AWS2::InstanceRes, ip_or_hostname:Any)experimental Source: autoload/AWS2.ngs:1085
Declarative primitive for adding ssh host fingerprints of AWS Instance resource to known hosts.
AWS2::pollute(do_warn:Any=true) Source: autoload/AWS2.ngs:1855
Undocumented
Doc::transform(p:Doc::Part, transformer:Any) Source: autoload/Doc.ngs:100
Undocumented
Doc::transform(dps:Arr, transformer:Any) Source: autoload/Doc.ngs:105
Undocumented