Fun type

Function type: native method, user defined method, or a multimethod

Methods

%(x:Any, cb:Fun) Source: stdlib.ngs:1914
Each operator. Same as calling x.each(cb)

Example

[1,2,3,4] % echo
*(cb:Fun, n:Int) Source: stdlib.ngs:8539
Call cb n times without any parameters and accumulate the results.

Example

a = Box * 2; a[0] is Box and a[1] is Box and a[0] !== a[1]  # true
+(f:Fun, g:Fun) Source: stdlib.ngs:810
Compose functions

Returns

Fun f(g(...))

Example

F reject(h:Hash, predicate:Fun) h.filter(not + predicate)
.(x:Any, f:Fun)EXPERIMENTAL Source: stdlib.ngs:804
Undocumented

Automatically called by NGS for syntax

x.{ ... }

Returns

f(x)
/(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
::(x:Any, f:Fun) Source: stdlib.ngs:461
Executes f(x)

Returns

x
=~(x:Any, f:Fun, _mc:MatchContext) Source: stdlib.ngs:1433
Undocumented

Returns

f(x).Bool()
\(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
acquire(l:Lock, cb:Fun) Source: stdlib.ngs:2818
Call cb with lock l held. Releases the lock after cb returns or throws.

Example

l = Lock()
...
l.acquire(F() {
  modify_global_state_safely(...)
})
acquire(c:Cond, cb:Fun) Source: autoload/globals/Cond.ngs:63
Acquire the related lock
all(e:Eachable2, predicate:Fun) Source: stdlib.ngs:4004
Checks whether all of the key-value pairs satisfies the predicate: predicate(k, v)

Returns

Bool
any(e:Eachable2, predicate:Fun) Source: stdlib.ngs:3989
Checks whether any of the key-value pairs satisfies the predicate: predicate(k, v)

Returns

Bool
apply(x:Eachable1, f:Fun) Source: stdlib.ngs:817
Applies f to arguments in x Same as calling f(*x)
apply(x:Eachable2, f:Fun) Source: stdlib.ngs:824
Applies f to arguments in x Same as calling f(**x)
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(f:Fun, t:Type, msg:Str='Assertion failed') Source: stdlib.ngs:373
Throws AssertFail with given function does not throw exception of the given type.

Parameters

fFun
tSubtype of Exception

Returns

The exception

Example

assert({1/0}, DivisionByZero)
block(body:Fun) Source: stdlib.ngs:224
Undocumented

Automatically called by NGS for syntax

block NAME BODY

Example

block b { calc(); if answer_found then b.return(42); more_calc(); another_answer }
cached(cb:Fun) Source: stdlib.ngs:9442
Cache cb results. Runs cb only once. TODO: Support arguments.

Returns

New function which wraps cb.

Example

my_func = cached( { expensive(); calculation(); steps(); result } )
use_result_of(my_func())
...
use_result_of(my_func())
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
collector(al:ArrLike, body:Fun) Source: stdlib.ngs:2096
Defines collector { ... collect(...) ... } behaviour for ArrLike. Very similar to collector for Arr. See collector(Arr,Fun).
collector(s:Set, body:Fun) Source: stdlib.ngs:2479
Defines collector { ... collect(...) ... } behaviour for Set.
collector(a:Arr, body:Fun) Source: stdlib.ngs:3013
Defines collector { ... collect(...) ... } behaviour for arrays

Parameters

aInitial array
bodyThe body after collector keyword and possible initial value, wrapped in a function "collector THIS_CODE" or "collector/my_init THIS_CODE"

Returns

Constructed array

Example

items = collector {
  collect(10)
  for(i;2) collect(i)
  collect(20)
}
echo(items)  # Outputs: [10,0,1,20]

# Or start with few items:
items = collector/[100,200] {
  collect(10)
  for(i;2) collect(i)
  collect(20)
}
echo(items)  # Outputs: [100,200,10,0,1,20]
collector(h:Hash, body:Fun) Source: stdlib.ngs:3027
Defines collector { ... collect(...) ... } behaviour for hashes

Parameters

hInitial hash
bodyThe body after collector keyword and initial value, wrapped in a function "collector/{'my': 'hash'} THIS_CODE"

Returns

Constructed Hash

Example

arr = [{"Name": "n1", "Value": "v1"},{"Name": "n2", "Value": "v2"}]
my_hash = collector/{}
	arr.each(F(elt) collect(elt.Name, elt.Value))
echo(my_hash)  # Outputs: {n1=v1, n2=v2}
collector(n:Int, body:Fun) Source: stdlib.ngs:3038
Defines collector { ... collect(...) ... } behaviour for integers (summarizes collected items).

Parameters

nInitial number
bodyThe body after collector keyword and initial value, wrapped in a function "collector/100 THIS_CODE"

Returns

The sum

Example

collector/0 { (1...10).each(collect) }  # 55
collector(s:Str, body:Fun) Source: stdlib.ngs:3048
EXPERIMENTAL! Do not use!
collector(s:Stats, body:Fun) Source: stdlib.ngs:5582
Undocumented
count(e:Eachable2, predicate:Fun) Source: stdlib.ngs:4187
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: predicate(k, v)

Returns

Int

Example

{'a': 1, 'b': 2, 'c': 11}.count(F(k, v) v>10)  # 1
deeper(mc:MatchContext, cb:Fun) Source: stdlib.ngs:1167
Undocumented
deeper(mc:MatchContext, new_fields:Hash, cb:Fun) Source: stdlib.ngs:1174
Undocumented
Diff(a:Arr, b:Arr, eq:Fun)experimental Source: stdlib.ngs:4857
EXPERIMENTAL! Do not use! Compare arrays using eq as equality test. 2*n*m comparisons

Returns

ArrDiff
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}>'
each(mm:MultiMethod, cb:Fun) Source: stdlib.ngs:519
Call cb for each method of the MultiMethod

Example

echo.each(F(method) echo("${method.params().name.join(", ")}"))
each(s:Success, fun:Fun) Source: stdlib.ngs:1054
Run fun with wrapped value.
each(f:Failure, fun:Fun) Source: stdlib.ngs:1064
No-op, returns f

Returns

f
each(al:ArrLike, cb:Fun) Source: stdlib.ngs:2070
Call cb for each element in the underlying array.

Returns

al
each(hl:HashLike, cb:Fun) Source: stdlib.ngs:2267
Iterate over keys and values.

Returns

hl

Example

my_hashlike.each(F(k, v) echo("$k=$v"))
each(s:Set, cb:Fun) Source: stdlib.ngs:2414
Call cb for each value in the set

Returns

s
each(r:NumRange, cb:Fun) Source: stdlib.ngs:2920
Iterates over the elements of r, passing each in turn to cb.

Parameters

cbFunction to be called with values from r

Returns

r

Example

s=0
(1...10).each(F(i) { global s; s+=i })
echo(s)  # Outputs: 55
each(arr:Arr, cb:Fun) Source: stdlib.ngs:3296
Iterates over the elements of arr, passing each in turn to cb along with args: cb(ITEM)

Parameters

cbFunction to be called with values from arr

Returns

arr

Example

s=0
[1,2,3].each(F(i) { global s; s+=i })
echo(s)  # Outputs: 6
each(arr:Arr, n:Int, cb:Fun) Source: stdlib.ngs:3345
Process each N elements of an Array at a time. Throws InvalidArgument if number of items in arr is not divisible by n. cb is called as cb(eltI, ..., eltJ) where I is multiple of n and J is I+n-1

Parameters

arrItems to iterate in chunks of n
nNumber of items in chunk
cbFunction to be called with values from arr

Returns

arr

Example

[1,2,3,4].each(2, F(a, b) echo("$a - $b"))  # Outputs: "1 - 2" and on the next line "3 - 4"
each(h:Hash, cb:Fun) Source: stdlib.ngs:3981
Iterate a Hash.

Parameters

hHash to iterate
cbFunction to call with successive keys and values

Returns

h

Example

{"a": 1, "b": 2}.each(F(k, v) echo("$k=$v"))  # Outputs: "a=1" and on the next line "b=2"
each(fb:FullBox, cb:Fun) Source: stdlib.ngs:4543
Call cb with the value of the FullBox

Returns

fb

Example

Box(10).each(echo)  # Output: 10
each(eb:EmptyBox, cb:Fun) Source: stdlib.ngs:4548
Do nothing

Returns

eb

Example

Box(null).each(echo)  # No output
each(n:Int, cb:Fun) Source: stdlib.ngs:4987
Iterate from zero up to but not including n

Parameters

cbFunction to call with current number

Returns

n

Example

10.each(echo)  # Outputs numbers from 0 to 9 inclusive, one on each line
each(s:Str, cb:Fun) Source: stdlib.ngs:5100
Iterates over all string characters (currently bytes).

Parameters

cbFunction to be called with each character from s

Returns

s

Example

"abc".each(echo)
# Output:
# a
# b
# c
each(d:Dir, cb:Fun) Source: stdlib.ngs:6293
Call cb for each entry in the directory with a subtype of Path as an argument

Returns

d
each(rd:ResDef, cb:Fun) Source: autoload/globals/Res.ngs:79
Call cb with properties of each found resource

Returns

rd

Example

AWS::Instance().each(F(i) echo(i.InstanceId))
each(i:Iter, cb:Fun) Source: autoload/globals/Iter.ngs:95
Calls cb with each element from i

Returns

i

Example

Iter(10).each(echo)  # Prints 0 to 9
each(t:Table, cb:Fun) Source: autoload/globals/Table.ngs:96
Please do not use. This method might change. Call cb with each table row.
each(t:Table, cb:Fun) Source: autoload/globals/Table2.ngs:236
Please do not use. This method might change. Call cb with each table row.
each_chunk(e:Eachable1, n:Int, cb:Fun)experimental Source: stdlib.ngs:3895
Call cb with array of maximum length of n, repeatedly for all items of e. TODO: better doc, rename to each() to be consistent with each(Arr, Int, Fun)?
each_group_test(tr:TestsResults, cb:Fun) Source: autoload/globals/TestsResults.ngs:53
Undocumented
each_idx_key_val(hl:HashLike, cb:Fun) Source: stdlib.ngs:2282
Undocumented
each_idx_key_val(h:Hash, cb:Fun) Source: stdlib.ngs:4041
Iterate a Hash.

Parameters

hHash to iterate
cbFunction to call with successive indexes, keys and values

Returns

h

Example

{"a": 1, "b": 2}.each_idx_key_val(F(idx, k, v) echo("[$idx] $k=$v"))
# Outputs: "[0] a=1" and on the next line "[1] b=2"
each_idx_val(e:Eachable1, cb:Fun) Source: stdlib.ngs:3307
Iterates over elements of e, passing each in turn to cb along with index and args: cb(INDEX, ITEM)

Returns

e

Example

"abc".each_idx_val(F(idx, val) echo("Element #$idx equals to $val"))
each_idx_val(arr:Arr, cb:Fun) Source: stdlib.ngs:3318
Iterates over the elements of arr, passing each in turn to cb along with index and args: cb(INDEX, ITEM)

Returns

arr

Example

[10,20,30].each_idx_val(F(idx, val) echo("Element #$idx equals to $val"))
each_ik_val(e:Eachable1, cb:Fun) Source: stdlib.ngs:4473
Same as each_idx_val() but only for e that is not Int or Str. Mnemonic: each index-or-key value.

Returns

e
each_ik_val(e:Eachable2, cb:Fun) Source: stdlib.ngs:4479
Same as each(e, cb). Mnemonic: each index-or-key value.

Returns

e
eachk(h:Hash, cb:Fun) Source: stdlib.ngs:4020
Iterate a Hash.

Parameters

hHash to iterate
cbFunction to call with successive keys

Returns

h
eachv(h:Hash, cb:Fun) Source: stdlib.ngs:4028
Iterate a Hash.

Parameters

hHash to iterate
cbFunction to call with successive values

Returns

h
filter(hl:HashLike, predicate:Fun) Source: stdlib.ngs:2294
Filter hash. Build new HashLike with kev-value pairs selected by predicate.

Parameters

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

Returns

value of the same type as hl

Example

my_hashlike.filter(F(k, v) k == 'a')
filter(h:Hash, predicate:Fun) Source: stdlib.ngs:4115
Filter a hash. Build new hash with kev-value pairs selected by the given predicate.

Parameters

hSource hash
predicateTest function to be called with one key and one value at a time: predicate(k, v)

Example

{'a': 1, 'b': 2}.filter(F(k, v) k == 'a')  # {'a': 1}
filter(rd:ResDef, predicate:Fun) Source: autoload/globals/Res.ngs:92
Create new resource definition by filtering resources of rd.

Parameters

rdOriginal resource definition. Not modified.

Returns

ResDef

Example

# Get instances with last private IP octet less than 20:
AWS::Instance().filter({A.PrivateIpAddress.split(".")[-1].Int()<20})
finally(b:Block, cleanup:Fun)experimental Source: stdlib.ngs:260
Add function to run before exiting the block. The functions added will be run in reverse order.
finally(body:Fun, cleanup:Fun) Source: stdlib.ngs:3084
Run cleanup after successful execution of body or exception in body

Parameters

bodyMain code to execute
cleanupCleanup code to execute

Returns

Whatever body call returns

Example

finally(
  { while entry = c_readdir(d) { ... } },
  { ... c_closedir(d) ...}
)
# Alternative function call syntax:
finally(
  body = {
    while entry = c_readdir(d) {
      cb(Path(dirname / entry.d_name, subtype=subtype))
    }
  }
  cleanup = {
    r = c_closedir(d)
    r != 0 throws DirFail('Failed to close directory after listing').set('dirname', dirname)
  }
)
flat_map(e:Eachable1, mapper:Fun) Source: stdlib.ngs:1587
Map and flatten. Applies mapper to each element of e, collects results, and flattens the results (one level).

Example

[2,0,4].flat_map(F(e) Result({ 12 / e}).Box())  # [6, 3]
[2,0,4].flat_map(F(e) [1, e*2])  # [1,4, 1,0, 1,8]
get_and_update(h:Holder, cb:Fun) Source: stdlib.ngs:4723
Extract a value and modify .val in place.

Parameters

cbCalled with the old value. Returns [value_to_return, new_value_to_hold].

Returns

cb(...)[0]

Example

h = Holder([1, 2, 3])
h.get_and_update(F(a) [a[0], a[1..null]])  # 1
h.val  # [2, 3]
group(e:Eachable1, k:Fun, v:Fun=method) Source: stdlib.ngs:4388
Group items from e by key returned by k

Returns

Hash with Arr values

Example

["ab", "ac", "ba", "bc", "bd"].group(F(x) x[0])  # {a=[ab,ac], b=[ba,bc,bd]}
[["a", 1], ["b", 2], ["a", 3]].group(X[0], X[1])  # {"a": [1,3], "b": [2]}
Hash(e:Eachable1, cb:Fun) Source: stdlib.ngs:4281
Create a Hash from keys in Eachable1 using cb for values calculation

Parameters

eKeys of the hash to build
cbFunction to be called with one key at a time. Should calculate a value for the given key.

Returns

Hash

Example

Hash([1,2], F(x) x*2)  # {1: 2, 2: 4}
init(t:Transformed, transformation:Fun, pattern:Any) Source: stdlib.ngs:1353
Undocumented
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(t:Thread, f:Fun) Source: stdlib.ngs:5659
Creates and runs a thread. The code that the created thread runs is f without arguments.
init(t:Thread, name:Str, f:Fun) Source: stdlib.ngs:5664
Creates and runs a thread. The code that the created thread runs is f without arguments.
init(i:MapIter, upstream_iter:Iter, mapper:Fun) Source: autoload/globals/Iter.ngs:113
EXPERIMENTAL! Do not use!
init(i:FunIter, f:Fun) Source: autoload/globals/Iter.ngs:195
Undocumented
init(t:Test, name:Str, body:Fun) Source: autoload/globals/test.ngs:249
Test constructor. Inside ns { }, also sets the namespace's member name to the test.

Returns

Test

Example

t = Test("addition", { assert(1 + 1, 2) })
n = ns { Test("addition", { assert(1 + 1, 2) }) }  # n.addition is the Test
init(mp:MethodParams, f:Fun) Source: autoload/globals/MethodParams.ngs:5
Undocumented
init(md:MethodDescription, method:Fun)
Undocumented
init(md:MethodDescription, containing_nd:NamespaceDescription, name:Str, mmd:MultiMethodDescription, method:Fun)
Undocumented
init(md:MethodDescription, containing_nd:NamespaceDescription, name:Str, method:Fun)
Undocumented
instantiate_param_dflt(f:Fun) Source: stdlib.ngs:496
Returns f
Iter(f:Fun) Source: autoload/globals/Iter.ngs:192
Undocumented
lines(s:Str, cb:Fun) Source: stdlib.ngs:5363
Split s to strings using end-of-line separators and call cb for each one of the lines. TODO: More efficient implementation, which would not have temporary array of all lines.

Parameters

cbFunction to be called with each line
lines(f:File, cb:Fun) Source: stdlib.ngs:6745
Iterate over lines of the file

Parameters

fClosed File
cbfunction to call with successive lines from the file
lines(p:Process, cb:Fun) Source: stdlib.ngs:7795
Iterate lines of Process' stdout, calling cb with successive lines. Warning: current implementation waits for the process to finish, accumulates all its stdout, and only then starts calling cb for each line.
lines(pp:ProcessesPipeline, cb:Fun) Source: stdlib.ngs:7811
Wait for pp and return call cb for each line of stdout of last process. Warning: current implementation waits for the processes to finish, accumulates all stdout of the last process, and only then starts calling cb for each line.

Returns

Arr of Str
lines(f:MaybeFile, cb:Fun) Source: autoload/globals/MaybeFile.ngs:8
Like lines(File) but cb is never called if the file is not present
map(s:Success, fun:Fun) Source: stdlib.ngs:1060
Run fun with wrapped value. If exception is thrown, Failure is returned; otherwise Success with new value is returned.

Returns

Result
map(f:Failure, fun:Fun) Source: stdlib.ngs:1068
No-op, returns f

Returns

f
map(e:Eachable, mapper:Fun) Source: stdlib.ngs:1579
Map e to an Arr (array) of values using mapper.

Parameters

eObject of any type that has each(e, callback) implemented

Returns

Arr

Example

[1,2,3].map(X*4)  # [4,8,12]
map(arr:Arr, n:Int, mapper:Fun) Source: stdlib.ngs:3366
Map each N elements of an Array at a time. mapper is called as cb(eltI, ..., eltJ) where I is multiple of n and J is I+n-1 Throws InvalidArgument if number of items in arr is not divisible by n. mapper is called as mapper(eltI, ..., eltJ) where I is multiple of n and J is I+n-1

Parameters

arrItems to iterate in chunks of n
nNumber of items in chunk
mapperFunction to be called with values from arr

Returns

Arr

Example

[1,2,3,4].map(2, F(a,b) "$a=$b").join("&")  # Outputs: 1=2&3=4
map(h:Hash, mapper:Fun) Source: stdlib.ngs:4053
Map a Hash

Parameters

hHash with source keys and values
mapperFunction to be called with keys and values from h

Returns

Arr

Example

{'a': 1, 'b': 2}.map(F(k, v) "${k}-$v")  # ['a-1', 'b-2']
map(fb:FullBox, mapper:Fun) Source: stdlib.ngs:4533
Map FullBox value

Parameters

mappermapper to be called with the FullBox value

Returns

FullBox with value returned by mapper

Example

Box(10).map(X*2)  # <FullBox val=20>
map(eb:EmptyBox, mapper:Fun) Source: stdlib.ngs:4538
Do nothing

Returns

eb

Example

EmptyBox().map(X*2)  # <EmptyBox>
map(i:Iter, mapper:Fun) Source: autoload/globals/Iter.ngs:129
EXPERIMENTAL! Do not use!
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
map_idx_key_val(hl:HashLike, mapper:Fun) Source: stdlib.ngs:2287
Undocumented
map_idx_key_val(h:Hash, mapper:Fun) Source: stdlib.ngs:4063
Map a Hash

Parameters

hHash with source keys and values
mapperFunction to be called with sequential zero-based index, keys and values from h

Returns

Arr

Example

{'a': 1, 'b': 2}.map_idx_key_val(F(i, k, v) "${i}-${k}-$v")  # ['0-a-1', '1-b-2']
map_idx_val(e:Eachable1, mapper:Fun) Source: stdlib.ngs:3328
Map an Eachable1 to an Arr (array) of values using mapper mapper is called as mapper(INDEX, ITEM)

Returns

New Arr

Example

echo("Array items: " + ArrLike().push(10).push(20).push(30).map_idx_val(F(idx, val) "[$idx]=$val").join(", "))
# Outputs: Array items: [0]=10, [1]=20, [2]=30
mapk(h:Hash, mapper:Fun) Source: stdlib.ngs:4072
Map Hash keys. Build new Hash with same values as in h but keys mapped by mapper.

Parameters

hSource hash
mapperFunction to be called with keys

Returns

Hash

Example

mapk({"a": 1}, F(k) k+"z")  # {"az": 1}
mapkv(h:Hash, mapper:Fun) Source: stdlib.ngs:4103
Map Hash keys and values. Build new Hash with keys and values mapped by mapper.

Parameters

hSource hash
mapperFunction to be called with keys and values

Example

mapkv({"a": 1}, {[A+"zz", B+10]})  # {"azz": 11}
mapo(e:Eachable1, mapper:Fun)experimental Source: stdlib.ngs:1605
EXPERIMENTAL! Do not use! Map e to same type. Mnemonics: "map original" / "MAP to Original type".

Parameters

eobject of any type that has each(e, callback) implemented Eachable1. WARNING: instances of same type as e must have empty constructor and push() method.

Returns

Of same type as e

Example

Set([1,2]).mapo(X*2)  # Set([2,4])
mapo(s:Str, mapper:Fun) Source: stdlib.ngs:5408
Map a string, character by character.

Returns

Str

Example

"abcd".mapo(F(x) if x == "b" then "X" else x)  # "aXcd"
"abcd".mapo(X.when("b", "*"))  # "a*cd"
mapv(h:Hash, mapper:Fun) Source: stdlib.ngs:4091
Map Hash values. Build new Hash with same keys as in h but values mapped by mapper.

Parameters

hSource hash
mapperFunction to be called with values

Returns

Hash

Example

LEN = 3
lines_ = read("/usr/share/dict/words").lines()
long_lines = lines_.filter({A.len()>LEN})
prefix_to_lines = long_lines.group(F(line) line[0..LEN])  # {"pfx1": ["pfx1a", "pfx1b", ...], "pfx2": ["pfx2a", "pfx2b", ...], ...}
prefix_to_count = prefix_to_lines.mapv(len)  # {"pfx1": 30, "pfx2": 35, ...}
top = prefix_to_count.Arr().sort(F(a, b) b[1] <= a[1]).Hash()
top .= limit(10)
echo(top)  # Outputs: {con=1219, dis=1001, pro=808, pre=607, com=600, int=543, tra=498, ove=431, per=422, imp=421}
merge_sorted(a:Arr, b:Arr, lte:Fun) Source: stdlib.ngs:3824
Merge sorted arrays.

Parameters

lteLess-then-or-equal function to use for comparison of items in a and b

Returns

Arr

Example

merge_sorted([1,3,10], [0, 7], (<=))  # [0, 1, 3, 7, 10]
ns(body:Fun) Source: stdlib.ngs:105
Run namespace body

Automatically called by NGS for syntax

ns { BODY }

Returns

Whatever body call returns
ns(body:Fun) Source: stdlib.ngs:5870
Run namespace body with DynVar(Namespace) bound to the namespace

Automatically called by NGS for syntax

ns { BODY }

Returns

Whatever body call returns
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)
opt_prop(rd:ResDef, name:Str, props:Hash, cb:Fun) Source: autoload/globals/Res.ngs:213
Run cb with optional resource property if it exists, uses opt_prop(ResDef, Str, Hash)
paginate(body:Fun) Source: stdlib.ngs:8044
Undocumented
partial(f:Fun, *bind_args:Arr)deprecated Source: stdlib.ngs:788
Returns partially-applied function

Parameters

fThe base function
partial_tail(f:Fun, *bind_args:Arr)deprecated Source: stdlib.ngs:796
Same as partial() but the bound arguments are last ones
pmap(e:Eachable1, mapper:Fun) Source: stdlib.ngs:5709
Parallel map. Runs mapper in threads. Each thread processes one element from the array but this might change in future (preserving the total number of calls to mapper and the order of results). Number of threads is limited to the lower of the two: processors * 100 or 1000.

Returns

Arr, result of applying mapper to elements of e, preserving the order.

Example

pages_texts = abs_pages_urls.pmap(F(url)  `lynx -dump $url`)
pmap(e:Eachable1, threads:Int, mapper:Fun) Source: stdlib.ngs:5730
Parallel map. Runs mapper in "threads" total threads.

Parameters

eEachable1 to be mapped
threadsnumber of threads to use
mappercalled with elements from e

Returns

Arr, result of applying mapper to elements of e, preserving the order.

Example

pages_texts = abs_pages_urls.pmap(F(url)  `lynx -dump $url`)
ptimes(n:Int, cb:Fun) Source: stdlib.ngs:5764
Run cb in n parallel threads. Each thread runs one cb but this might change in future (preserving the total n calls to cb).
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, (+))
reduce(e:Eachable1, f:Fun) Source: stdlib.ngs:1861
Combine items to a single value using the supplied binary function First f is applied to the first two elements of e then on each step f is applied to previous result and next element of e. Throws EmptyEachableFail if e has no elements. If e has only one element, that element is returned.

Parameters

eobject of any type that has each(e, callback) implemented
fThe combining function

Example

F sum(e) e.reduce((+))
reject(h:Hash, predicate:Fun) Source: stdlib.ngs:4125
h.filter(not + predicate)
replace(s:Str, r:RegExp, mapper:Fun) Source: stdlib.ngs:8504
Replace all occurrences of r

Parameters

mapperFunction that will be called with one matching string at a time that provides the replacement

Returns

Str

Example

"x10ab20c30y".replace(/[0-9]+/, F(match_text) "[$match_text]")  # "x[10]ab[20]c[30]y"
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"` })
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
sort(a:Arr, lte:Fun=method) Source: stdlib.ngs:3847
Sort an array.

Parameters

lteLess-then-or-equal function to use for comparison of the items in a

Returns

Arr

Example

sort([0,5,3,-1], (<=))  # [-1, 0, 3, 5]
sort(a:Arr, field:Str, lte:Fun=method) Source: stdlib.ngs:3862
Sort an array based on field value

Parameters

lteLess-then-or-equal function to use for comparison of the items' fields

Returns

Arr

Example

[{'x': 1}, {'x': 5}, {'x': 3}].sort('x')  # [{'x': 1}, {'x': 3}, {'x': 5}]
sort(h:Hash, lte:Fun=method) Source: stdlib.ngs:4436
Sort a Hash.

Parameters

lteLess-then-or-equal function to use for comparison of the keys in h

Returns

Hash

Example

{"b": 2, "c": 3, "a": 1}.sort()  # {"a": 1, "b": 2, "c": 3}
sortk(h:Hash, lte:Fun=method) Source: stdlib.ngs:4196
Sort Hash by keys

Returns

Hash

Example

{'b': 2, 'c': 11, 'a': 1}.sortk()  # {'a': 1, 'b': 2, 'c': 11}
sortv(h:Hash, lte:Fun=method)experimental Source: stdlib.ngs:4204
Undocumented
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()
test(name:Str, f:Fun) Source: autoload/globals/test.ngs:16
Runs f as a test.

Parameters

nameHuman readable name of the test.
fA Fun that will either throw TestFail, return TestMessage. Other values are ignored by the testing framework.
test(results:TestsResults, group:Str, name:Str, f:Fun, critical:Bool=true) Source: autoload/globals/test.ngs:32
EXPERIMENTAL! Do not use! Runs f as a test in a test group
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]
}
time(cb:Fun) Source: stdlib.ngs:9003
Measure running time of cb in microseconds

Returns

Int
times(n:Int, cb:Fun) Source: stdlib.ngs:4998
Call cb n times without arguments.

Parameters

cbFunction to call

Example

r=0; 5.times(F() r=r+2);  # r is now 10
uniq(e:Eachable1, cb:Fun=method) Source: stdlib.ngs:3423
Return unique values. Warning: uses Hash so comparison is not using == but a built-in hash keys comparison.

Returns

Of same type as e

Example

[1,2,2,3,4,4].uniq()  # [1,2,3,4]
[{"a": 1, "z": 10}, {"a": 1, "z": 20}, {"a": 2, "z": 30}].uniq(X.a)  # [{"a": 1, "z": 10}, {"a": 2, "z": 30}]
Value(x:Fun, *args:Arr) Source: stdlib.ngs:839
Used for converting default values or functions to values

Returns

x(*args)
wait(c:Cond, check_condition:Fun, cb:Fun) Source: autoload/globals/Cond.ngs:27
Wait for condition

Parameters

check_conditionwhen returns true, cb is executed
cbcallback to be executed when c is signaled with notify() or notify_all() and check_condition returns true

Returns

result of cb()
AWS::regions(cb:Fun) Source: autoload/globals/AWS.ngs:94
Call cb in parallel threads, each with AWS region name as argument.

Parameters

cbMust return an array. regions() sets .Region in the result and flattens the results

Returns

Arr

Example

ins = AWS::regions({ ``aws ec2 describe-instances --region $A $*filters`` })
AWS2::regions(cb:Fun, regs:Arr=[]) Source: autoload/globals/AWS2.ngs:89
Call cb in parallel threads, each with AWS region name as argument.

Parameters

cbMust return an array. regions() sets ._Region in the result and flattens the results

Returns

Arr

Example

ins = AWS2::regions({ ``aws ec2 describe-instances --region $A $*filters`` })
Doc::each_child(p:Doc::Part, cb:Fun) Source: autoload/globals/Doc.ngs:82
Undocumented
Doc::map_children(p:Doc::Part, mapper:Fun) Source: autoload/globals/Doc.ngs:83
Undocumented
Doc::Transformer(x:Fun) Source: autoload/globals/Doc.ngs:87
Undocumented
Doc::visit(p:Doc::Part, cb:Fun, parents:Arr=[]) Source: autoload/globals/Doc.ngs:110
Undocumented