mixin

Funcs

Funcs : Funcs

meta mixin slots equals

Return if two values are equivalent

isEmpty

Return if a collection is empty

size

Return number of items in str, list, or grid

get

Get an item from a collection

getSafe

Get an item from a str, list, or grid safely when an index is out of bounds

first

Get the first item from an ordered collection or return null if the collection is empty

last

Get the last item from an ordered collection or return null if the collection is empty

has

If val is a Grid return if it has the given column name

missing

If val is a Grid return if it does not have given column name

index

Return the first match of x in val searching forward, starting at the specified offset index

indexr

Return the last match of x in val searching backward, starting at the specified offset index

contains

Return if val contains x

add

Add item to the end of a list and return a new list

addAll

Add all the items to the end of a list and return a new list

set

Set a collection item and return a new collection

merge

Merge two Dicts together and return a new Dict

insert

Insert an item into a list at the given index and return a new list

insertAll

Insert a list of items at the given index and return a new list

remove

Remove an item from a collection and return a new collection

stream

Create new stream from given collection

streamCol

Create a new stream for the cell values of the given column

collect

Collect stream into a in-memory list or grid

limit

Truncate stream after given limit is reached

skip

Skip the given number of items in a stream

sort

Sort a list or grid

sortDis

Sort a grid by row display name - see Grid.sortDis

Examples

sortr

Reverse sort a list or grid

each

Iterate the items of a collection

eachWhile

Iterate the items of a collection until the given function returns non-null

map

Map list, dict, or grid by applying the given mapping function

flatMap

Map each item in a list or grid to zero or more new items as a flattened result

find

Find the first matching item in a list or grid by applying the given filter function

findAll

Find all the items in a list, dict, or grid by applying the given filter function

filter

Apply a filter expression to a collection of dicts

all

Return if all the items in a list, dict, or grid match the given test function

any

Return if any the items in a list, dict, or grid match the given test function

reduce

Reduce a collection to a single value with the given reducer function

moveTo

Find the given item in a list, and move it to the given index

unique

Return the unique items in a collection

flatten

Flatten a list to a single level

gridRowsToDict

Convert grid rows into a dict of name/val pairs

gridColsToDict

Convert grid columns into a dict of name/val pairs

gridColKinds

Given a grid return the types used in each column as a grid with the following

fold

Fold a list or stream into a single value using given folding function

foldCol

Fold the values of the given column into a single value

foldCols

Fold a set of columns in each row into a new folded column and return a new grid

foldStart

The fold start marker value

foldEnd

The fold end marker value

count

Fold multiple values into their total count Return zero if no values

sum

Fold multiple values into their numeric sum

min

Compare two numbers and return the smaller one

max

Compare two numbers and return the larger one

avg

Fold multiple values into their standard average or arithmetic mean

spread

Fold multiple values to compute the difference between the max and min value

marker

Get the marker value singleton Marker.val

none

Get the none value singleton None.val

removeMarker

This method is for backward compatibility only - use none()

na

Get NA not-available singleton NA.val

isTagName

Return if the given string is legal tag name - see Etc.isTagName

toTagName

Given arbitrary string, convert to a safe tag name - see Etc.toTagName

names

Get the list of names used by a given dict

vals

Get the list of values used by a given dict

trap

Function for the -> operator

meta

Get the meta-data from a grid or col as a dict

cols

Get the columns from a grid as a list

col

Get a column by its name

colNames

Get the column names a list of strings

name

If val is a Col, get the column name

setMeta

Return new grid with grid level meta-data replaced by given meta Dict

addMeta

Return new grid with additional grid level meta-data tags

join

Join two grids by column name

joinAll

Join a list of grids into a single grid

addCol

Add a column to a grid by mapping each row to a new cell value

addCols

Add grid b as a new set of columns to grid a

renameCol

Return a new grid with the given column renamed

renameCols

Return a new grid with multiple columns renamed

reorderCols

Return a new grid with the columns reordered

setColMeta

Return a new grid with column meta-data replaced by given meta dict

addColMeta

Return a new grid with additional column meta-data

removeCol

Return a new grid with the given column removed

removeCols

Return a new grid with all the given columns removed

keepCols

Return a new grid with keeps the given columns, but removes all the others

addRow

Add an additional Dict row to the end of a grid

addRows

Add an list of rows to the end of a grid

rowToList

Get a grid row as a list of cells

colToList

Get a column as a list of the cell values ordered by row

transpose

Perform a matrix transpose on the grid

swizzleRefs

Given a grid of records, assign new ids and swizzle all internal ref tags

gridReplace

Replace every grid cell with the given from value with the to value

times

Call the specified function the given number of times passing the counter

isOdd

Return if an integer is an odd number

isEven

Return if an integer is an even number

abs

Return absolute value of a number, if null return null

isNaN

Return if val is the Number representation of not-a-number

nan

Return the Number representation of not-a-number

posInf

Return the Number representation positive infinity

negInf

Return the Number representation negative infinity

clamp

Clamp the number val between the min and max

today

Return today's Date according to context's time zone

yesterday

Return yesterday's Date according to context's time zone

now

Return current DateTime according to context's time zone

nowUtc

Return current DateTime in UTC

nowTicks

Return current time as nanosecond ticks since 1 Jan 2000 UTC

occurred

Return if a timestamp is contained within a Date range

start

Start value of a DateSpan, Span or a range

end

End value of a DateSpan, Span, or a range

thisWeek

DateSpan for this week as sun..sat (uses locale start of week)

thisMonth

DateSpan for this month as 1st..28-31

thisQuarter

DateSpan for this 3 month quarter

thisYear

DateSpan for this year Jan-1..Dec-31

pastWeek

DateSpan for last 7 days as today-7days..today

pastMonth

DateSpan for last 30days today-30days..today

pastYear

DateSpan for this past today-365days..today

lastWeek

DateSpan for week previous to this week sun..sat (uses locale start of week)

lastMonth

DateSpan for month previous to this month 1..28-31

lastQuarter

DateSpan for 3 month quarter previous to this quarter

lastYear

DateSpan for year previous to this year Jan-1..Dec-31

firstOfMonth

Get the first day of given date's month

lastOfMonth

Get the last day of the date's month

toDateSpan

Convert the following objects into a DateSpan

toSpan

Convert the following objects into a Span

numDays

Number of whole days in a span

eachDay

Iterate the days of a span

eachMonth

Iterate the months of a span

year

Get year as integer such as 2010 from date or datetime

month

Get month as integer between 1 to 12 from date or datetime

day

Get day of month as integer between 1 to 31 from date or datetime

hour

Get hour of day as integer between 0 to 23 from time or datetime

minute

Get minutes of the time as integer between 0 to 59 from time or datetime

second

Get seconds of the time as integer between 0 to 59 from time or datetime

weekday

Get weekday as integer from 0 to 6 of Date or DateTime

isWeekend

Does the given Date or DateTime fall on Sat or Sun

isWeekday

Does the given Date or DateTime fall on Mon, Tue, Wed, Thu, or Fri

tz

Get timezone as city name string in tzinfo database from datetime

dateTime

Construct a DateTime from a date, time, and timezone name

date

If val is a DateTime

time

If val is a DateTime

toTimeZone

Convert a DateTime or Span to another timezone

numDaysInMonth

Get the number of days in a given month

isLeapYear

Return if a year is a leap year

dst

Return if a DateTime is in daylight saving time

hoursInDay

Given a DateTime in a specific timezone, return the number of hours in the day

dayOfYear

Given a DateTime or Date, return the day of the year

weekOfYear

Given a DateTime or Date, return the week number of the year

startOfWeek

Return current locale's start of weekday

toJavaMillis

Given a DateTime return Number of milliseconds since Unix epoch

fromJavaMillis

Given Number of milliseconds since Unix epoch return a DateTime

isMetric

Given an optional value return true if the SI metric system should be used

unit

Given a number return its unit string or null

unitsEq

Return if the two numbers have the same unit

to

Convert a number to the given unit

as

Set the unit of a number

def

Lookup a def by its symbol name (Str or Symbol)

defs

List all definitions in the context namespace as Def[]

tags

List tag definitions in the context namespace as Def[]

terms

List term definitions (tags and conjuncts) in the context namespace as Def[]

conjuncts

List conjunct definitions in the context namespace as Def[]

func

Find a top-level function by name or by reference and return its tags

funcs

Find all the top-levels functions in the current project which match the given filter

curFunc

Get the current top-level function's tags

is

Return if the given instance inherits from the spec via nominal typing

debugType

Return a string of the given value's type

isNull

Return if an object is null

isNonNull

Return if an object is not null

isList

Return if an object is a list type

isDict

Return if an object is a dict type

isGrid

Return if an object is a grid type

isHisGrid

Return if an object is a grid that conforms to the history grid shape

isBool

Return if an object is a boolean type

isNumber

Return if an object is a number type

isDuration

Return if an object is a number type with a time unit

isRef

Return if an object is a ref type

isStr

Return if an object is a str type

isUri

Return if an object is a Uri type

isDate

Return if an object is a Date type

isTime

Return if an object is a Time type

isDateTime

Return if an object is a DateTime type

isFunc

Return if an object is a function type

isSpan

Return if an object is a span

isKeyword

Return if given string is an Axon keyword

toHex

Convert a number to a hexadecimal string

toRadix

Convert a number to its string representation in the given radix (base)

toStr

Convert an obj to its string representation

toList

If val is a list return it, otherwise return [val]

toGrid

Given an arbitrary object, translate it to a Grid via Etc.toGrid

colsToLocale

Localize column display names

toLocale

Get the localized string for the given tag name or qualified name

localeUse

Evaluate an expression within a specific locale

dis

Get display string for dict or the given tag

relDis

Get a relative display name

format

Format an object using the current locale and specified format pattern

parseBool

Parse a Str into a Bool, legal formats are "true" or "false

parseInt

Parse a Str into a integer number using the specified radix

parseFloat

Parse a Str into a Float

parseNumber

Parse a Str into a number with an option unit

parseUri

Parse a string into a Uri instance

parseDate

Parse a Str into a Date

parseTime

Parse a Str into a Time

parseDateTime

Parse a Str into a DateTime

parseRef

Parse a Str into a Ref

parseSymbol

Parse a Str into a Symbol

parseFilter

Parse a filter string into a Filter instance

parseSearch

Parse a search string into a Filter instance

filterToFunc

Convert a filter expression to a function which maybe used with findAll or find

parseUnit

Parse a Str into a standardized unit name

xstr

Construct decoded XStr instance

upper

Convert a char number or str to ASCII upper case

lower

Convert a char number or str to ASCII lower case

isSpace

Is number is whitespace char

isAlpha

Is number an ASCII alpha char

isAlphaNum

Is number an ASCII alpha-numeric char

isUpper

Is number an ASCII uppercase alphabetic char

isLower

Is number an ASCII lowercase alphabetic char

isDigit

Is number a digit in the specified radix

toChar

Convert a unicode char number into a single char string

Examples

split

Split a string by the given separator and trim whitespace

capitalize

Return this string with the first character converted to uppercase

decapitalize

Return this string with the first character converted to lowercase

trim

Trim whitespace from the beginning and end of the string

trimStart

Trim whitespace only from the beginning of the string

trimEnd

Trim whitespace only from the end of the string

startsWith

Return if Str starts with the specified Str

endsWith

Return if Str ends with the specified Str

replace

String replace of all occurrences of from with to

padl

Pad string to the left

padr

Pad string to the right

concat

Concatenate a list of items into a string

reMatches

Return if regular expression matches entire region of s

reFind

Find the first match of regular expression in s or return null if no matches

reFindAll

Find all matches of the regular expression in s

reGroups

Return a list of the substrings captured by matching the given regular operation against s

uriScheme

Get the scheme of a Uri as a string or null

uriHost

Get the host Uri as a string or null

uriPort

Get the port of a Uri as a Number or null

uriName

Get the name Str of a Uri (last item in path)

uriPath

Get the path segments of a Uri as a list of Strs

uriPathStr

Get the path a Uri as a string

uriBasename

Get the basename (last name in path without extension) of a Uri as a string

uriExt

Get the URI extension of a Uri as a string or null

uriIsDir

Return if the URI path ends in a slash

uriFrag

Return if the fragment identifier portion of the a URI after hash symbol

uriQueryStr

Return if the query portion of the a URI after question mark

uriPlusSlash

Adding trailing slash to the URI

uriEncode

Return the percent encoded string for this Uri according to RFC 3986

uriDecode

Parse an ASCII percent encoded string into a Uri according to RFC 3986

refGen

Generate a new unique Ref identifier

refDis

Given a ref return Ref.dis

refProjName

Given an absolute ref, return its project name

coord

Construct a Coord from two Numbers in decimal degrees

coordLat

Latitude of a Coord as a Number

coordLng

Longitude of a Coord as a Number

coordDist

Compute the great-circle distance between two Coords

echo

Write the str represenation of x to stdout and return x

eval

Evaluate an Axon string expression

evalToFunc

Evalate an Axon string expression to a function

call

Reflectively call a function with the given arguments

callByName

Reflectively call a function with arguments by name

toAxonCode

Convert a scalar, list, or dict value to its Axon code representation

parseAst

Parse Axon source code into an abstract syntax tree modeled as a tree of dicts

equals (a: Obj?, b: Obj?) => Obj?

Return if two values are equivalent. Unlike the standard == operator this function will compare the contents of collection values such as lists, dicts, and grids. For non-collection values, the result is the same as the == operator. This function does not work with lazy grids such as hisRead result.

isEmpty (val: Obj?) => Obj?

Return if a collection is empty: str, list, dict, or grid

size (val: Obj?) => Number

Return number of items in str, list, or grid

get (val: Obj?, key: Obj?) => Obj?

Get an item from a collection:

  • str(num): get character at index as int (same semantics as Fantom)
  • str(range): get string slice (same semantics as Fantom)
  • list(num): get item at given index (same semantics as Fantom)
  • list(range): get list slice at given index (same semantics as Fantom)
  • dict(key): get item with given key or return null
  • grid(num): get row at given index
  • grid(range): Grid.getRange

The get function maybe be accessed using the [] shortcut operator:

 list[3]  >>  list.get(3)

See Axon Language.

getSafe (val: Obj?, key: Obj?) => Obj?

Get an item from a str, list, or grid safely when an index is out of bounds:

  • str(num): get a character at index or null if index invalid
  • str(range): get safe slice or "" if entire range invalid
  • list(num): get item at given index or null is index invalid
  • list(range): get list slice with safe index
  • grid(num): get row at given index or null if index invalid
  • grid(range): Grid.getRange with safe range

first (val: Obj?) => Obj?

Get the first item from an ordered collection or return null if the collection is empty:

  • list: item at index 0
  • grid: first frow
  • stream: first item; see Streams

last (val: Obj?) => Obj?

Get the last item from an ordered collection or return null if the collection is empty:

  • list: item at index -1
  • grid: item at index -1
  • stream: last item; see Streams

has (val: Obj?, name: Str) => Obj?

If val is a Grid return if it has the given column name. If val is a Dict return if the given name is mapped to a non-null value.

missing (val: Obj?, name: Str) => Obj?

If val is a Grid return if it does not have given column name. If val is a Dict, return if the given name is not mapped to a non-null value.

index (val: Obj, x: Obj, offset: Number) => Obj?

Return the first match of x in val searching forward, starting at the specified offset index. A negative offset may be used to access from the end of string. Return null if no occurences are found:

  • if val is Str, then x is substring.
  • if val is List, then x is item to search.

indexr (val: Obj, x: Obj, offset: Number) => Obj?

Return the last match of x in val searching backward, starting at the specified offset index. A negative offset may be used to access from the end of string. Return null if no occurences are found:

  • if val is Str, then x is substring.
  • if val is List, then x is item to search.

contains (val: Obj, x: Obj?) => Bool

Return if val contains x:

  • if val is Str, then x is substring.
  • if val is List, then x is item to search.
  • if val is Range, then is x inside the range inclusively
  • if val is DateSpan, then is x a date in the span

add (val: Obj?, item: Obj?) => Obj?

Add item to the end of a list and return a new list.

addAll (val: Obj?, items: Obj?) => Obj?

Add all the items to the end of a list and return a new list.

set (val: Obj?, key: Obj?, item: Obj?) => Obj?

Set a collection item and return a new collection.

  • List: set item by index key
  • Dict: set item by key name

merge (a: Obj?, b: Obj?) => Obj?

Merge two Dicts together and return a new Dict. Any tags in b are added to a. If b defines a tag already in a, then it is overwritten by b. If a tag in b is mapped to None.val, then that tag is removed from the result.

insert (val: Obj?, index: Number, item: Obj?) => Obj?

Insert an item into a list at the given index and return a new list.

insertAll (val: Obj?, index: Number, items: Obj?) => Obj?

Insert a list of items at the given index and return a new list.

remove (val: Obj?, key: Obj?) => Obj?

Remove an item from a collection and return a new collection.

  • List: key is index to remove at
  • Dict: key is tag name

stream (val: Obj?) => Obj

Create new stream from given collection:

  • Grid: stream the rows
  • List: stream the items
  • Range: stream inclusive range of integers See Streams.

streamCol (grid: Grid, col: Obj) => Obj

Create a new stream for the cell values of the given column. See Streams.

collect (stream: Obj?, to: Func?) => Obj

Collect stream into a in-memory list or grid. See Streams.

limit (stream: Obj?, limit: Number) => Obj

Truncate stream after given limit is reached. See Streams.

skip (stream: Obj?, count: Number) => Obj

Skip the given number of items in a stream. See Streams.

sort (val: Obj, sorter: Obj?) => Obj?

Sort a list or grid.

If sorting a list, the sorter should be a function that takes two list items and returns -1, 0, or 1 (typicaly done with the <=> operator. If no sorter is passed, then the list is sorted by its natural ordering.

If sorting a grid, the sorter can be a column name or a function. If a function, it should take two rows and return -1, 0, or 1.

Examples:

// sort string list
["bear", "cat", "apple"].sort

// sort string list by string size
["bear", "cat", "apple"].sort((a,b) => a.size <=> b.size)

// sort sites by area
readAll(site).sort((a, b) => a->area <=> b->area)

sortDis (val: Grid) => Obj?

Sort a grid by row display name - see Grid.sortDis

Examples:

// read all sites and sort by display name
readAll(site).sortDis

sortr (val: Obj, sorter: Obj?) => Obj?

Reverse sort a list or grid. This function works just like sort except sorts in reverse.

each (val: Obj, fn: Func) => Obj?

Iterate the items of a collection:

  • Grid: iterate the rows as (row, index)
  • List: iterate the items as (value, index)
  • Dict: iterate the name/value pairs (value, name)
  • Str: iterate the characters as numbers (char, index)
  • Range: iterate the integer range (integer)
  • Stream: iterate items as (val); see Streams

eachWhile (val: Obj, fn: Func) => Obj?

Iterate the items of a collection until the given function returns non-null. Once non-null is returned, then break the iteration and return the resulting object. Return null if the function returns null for every item.

  • Grid: iterate the rows as (row, index)
  • List: iterate the items as (val, index)
  • Dict: iterate the name/value pairs (val, name)
  • Str: iterate the characters as numbers (char, index)
  • Range: iterate the integer range (integer)
  • Stream: iterate items as (val); see Streams

map (val: Obj, fn: Func) => Obj?

Map list, dict, or grid by applying the given mapping function.

If mapping a list, the mapping should be a function that takes (val) or (val, index). It should return the new value for that index.

If mapping a dict, the mapping should be a function that takes (val) or (val, name). It should return the new value for that name.

If mapping a grid, the mapping function takes (row) or (row,index) and returns a new dictionary to use for the row. The resulting grid shares the original's grid level meta. Columns left intact share the old meta-data, new columns have no meta-data. If the mapping function returns null, then that row is removed from the resulting grid (not mapped).

If mapping a range, then the mapping function takes (integer), and returns a list for each mapped integer inte the range.

If mapping a stream, the mapping functions takes (val). See Streams.

Examples:

 // create list adding ten to each number
 [1, 2, 3].map(v => v+10)   >>   [11, 12, 13]

 // create new list that turns strings into uppercase
 ["ape", "bee", "cat"].map(upper)    // ["APE, "BEE", "CAT"]

 // create dict adding ten to each value
 {a:1, b:2, c:3}.map(v => v+10)   >>   {a:11, b:12, c:13}

 // create grid with just dis, area column
 readAll(site).map(s => {dis:s->dis, area:s->area})

flatMap (val: Obj, fn: Func) => Obj?

Map each item in a list or grid to zero or more new items as a flattened result.

If mapping a list, the mapping should be a function that takes (val) or (val, index). It should return the a list of zero or more new values. See List.flatMap.

If mapping a grid, the mapping function takes (row) or (row,index) and returns a list of zero or more new Dict rows. See Grid.flatMap.

If mapping a stream, the mapping functions takes (val). See Streams.

Examples:

[1, 2, 3].flatMap(v => [v, v+10])   >>  [1, 11, 2, 12, 3, 13]

find (val: Obj, fn: Func) => Obj?

Find the first matching item in a list or grid by applying the given filter function. If no match is found return null.

If working with a list, the filter should be a function that takes (val) or (val, index). It should return true to match and return the item.

If working with a dict, the filter should be a function that takes (val) or (val, name). It should return true to match and return the item.

If working with a grid, the filter function takes (row) or (row, index) and returns true to match and return the row.

If working with a stream, the filter takes (val) and returns true to match. See Streams.

Examples:

// find first string longer than 3 chars
["ape", "bat", "charlie", "dingo"].find(x => x.size > 3)

// find first odd number
[10, 4, 3, 7].find(isOdd)

findAll (val: Obj, fn: Func) => Obj?

Find all the items in a list, dict, or grid by applying the given filter function. Also see find.

If working with a list, the filter should be a function that takes (val) or (val, index). It should return true to keep the item.

If working with a dict, the filter should be a function that takes (val) or (val, name). It should return the true to keep the name/value pair.

If working with a grid, the filter function takes (row) or (row, index) and returns true to keep the row. The resulting grid shares the original's grid meta and columns.

If working with a stream, the filter takes (val) and returns true to match. See Streams.

Examples:

// find all the strings longer than 3 chars
["ape", "bat", "charlie", "dingo"].findAll(x => x.size > 3)

// find even numbers
[0, 1, 2, 3, 4].findAll(isEven)

// find all the sites greater than 10,000ft from grid
readAll(site).findAll(s => s->area > 10_000ft²)

filter (val: Obj?, filter: Filter) => Obj

Apply a filter expression to a collection of dicts. The collection value may be any of the following:

  • Grid: returns new grid with filtered rows
  • Dict[]: returns list of filtered dicts (nulls are filtered out)
  • Col[]: returns list of columns filtered by their meta
  • Stream: filters stream of Dicts - see Streams

The filter parameter may one fo the following:

Examples:

// apply to a list of dicts
[{v:1}, {v:2}, {v:3}, {v:4}].filter(v >= 3)

// apply to a grid and return new grid with matching rows
readAll(equip).filter(meter)

// apply to a list of columns
read(ahu).toPoints.hisRead(yesterday).cols.filter(kind=="Bool")

// apply to a stream of dicts
readAllStream(equip).filter(siteMeter and elec and meter).collect

// apply search filter
readAll(equip).filter(parseSearch("RTU-1"))

all (val: Obj, fn: Func) => Obj?

Return if all the items in a list, dict, or grid match the given test function. If the collection is empty, then return true.

If working with a list, the function takes (val) or (val, index) and returns true or false.

If working with a dict, the function takes (val) or (val, name) and returns true or false.

If working with a grid, the function takes (row) or (row, index) and returns true or false.

If working with a string, the function takes (char) or (char, index) and returns true or false.

If working with a stream, then function takes (val) and returns true or false. See Streams.

Examples:

[1, 3, 5].all v => v.isOdd  >>  true
[1, 3, 6].all(isOdd)        >>  false

any (val: Obj, fn: Func) => Obj?

Return if any the items in a list, dict, or grid match the given test function. If the collection is empty, then return false.

If working with a list, the function takes (val) or (val, index) and returns true or false.

If working with a dict, the function takes (val) or (val, name) and returns true or false.

If working with a grid, the function takes (row) or (row, index) and returns true or false.

If working with a string, the function takes (char) or (char, index) and returns true or false.

If working with a stream, then function takes (val) and returns true or false. See Streams.

Examples:

[1, 3, 5].any v => v.isOdd  >>  true
[2, 4, 6].any(isOdd)        >>  false

reduce (val: Obj, init: Obj?, fn: Func) => Obj?

Reduce a collection to a single value with the given reducer function. The given function is called with each item in the collection along with a current accumulation value. The accumation value is initialized to init for the first item, and for every subsequent item it is the result of the previous item. Return the final accumulation value. Also see fold which is preferred if doing standard rollup such as sum or average.

If working with a list, the function takes (acc, val, index) and returns accumulation value

If working with a grid, the function takes (acc, row, index) and returns accumulation value

If working with a stream, then function takes (acc, val) and returns accumulation value See Streams.

Examples:

[2, 5, 3].reduce(0, (acc, val)=>acc+val)  >> 10
[2, 5, 3].reduce(1, (acc, val)=>acc*val)  >> 30

moveTo (list: List, item: Obj?, toIndex: Number) => List

Find the given item in a list, and move it to the given index. All the other items are shifted accordingly. Negative indexes may used to access an index from the end of the list. If the item is not found then this is a no op. Return new list.

Examples:

[10, 11, 12].moveTo(11, 0)  >>  [11, 10, 12]
[10, 11, 12].moveTo(11, -1) >>  [10, 12, 11]

unique (val: Obj, key: Obj?) => Obj?

Return the unique items in a collection. If val is a List then return List.unique. If val is a Grid then return Grid.unique where key must be a column name or list of column names.

Examples:

[1, 1, 2, 2].unique                 >> [1, 2]
grid.unique("geoState")             >> unique states
grid.unique(["geoCity", geoState"]) >> city,state combos

flatten (list: List) => Obj

Flatten a list to a single level. If given a list of grids, then flatten rows to a single grid. Also see List.flatten and Etc.gridFlatten.

Examples:

// flatten a list of numbers
[1, [2, 3], [4, [5, 6]]].flatten  >>  [1, 2, 3, 4, 5, 6]

// flatten a list of grids
["Carytown", "Gaithersburg"].map(n=>readAll(siteRef->dis==n)).flatten

gridRowsToDict (grid: Grid, rowToKey: Func, rowToVal: Func) => Dict

Convert grid rows into a dict of name/val pairs. The name/value pairs are derived from each row using the given functions. The functions take (row, index)

Example:

// create dict of sites with dis:area pairs
readAll(site).gridRowsToDict(s=>s.dis.toTagName, s=>s->area)

gridColsToDict (grid: Grid, colToKey: Func, colToVal: Func) => Dict

Convert grid columns into a dict of name/val pairs. The name/val paris are derived from each column using the given functions. The functions take (col, index)

Example:

// create dict of column name to column dis
read(temp).hisRead(today).gridColsToDict(c=>c.name, c=>c.meta.dis)

gridColKinds (grid: Grid) => Grid

Given a grid return the types used in each column as a grid with the following:

  • name: string name of the column
  • kind: all the different value kinds in the column separated by "|"
  • count: total number of rows with column with a non-null value Also see readAllTagNames().

Example:

readAll(site).gridColKinds

fold (val: Obj?, fn: Func) => Obj?

Fold a list or stream into a single value using given folding function. The folding function signature must be (val, acc) where val is the items being folded, and acc is an accumulator used to maintain state between iterations. Lifecycle of a fold:

  1. Call fn(foldStart, null), return initial accumulator state
  2. Call fn(item, acc) for every item, return new accumulator state
  3. Call fn(foldEnd, acc) return final result

See Streams for streaming details.

The fold will short-circuit and halt immediately if the folding function returns na() for the accumulator state. The result of the fold is na() in this case. A folding function should document its behavior when a collection contains na().

Built-in folding functions include:

Examples:

[1, 2, 3, 4].fold(max)  // fold list into its max value
[1, 2, 3, 4].fold(avg)  // fold list into its average value
[1, 2, na(), 3].fold(sum) // => na()

Example of writing your own custom fold function that used start/end values and has support for na():

 average: (val, acc) => do
   if (val == foldStart()) return {sum:0, count:0}
   if (val == foldEnd()) return acc->sum / acc->count
   if (val == na()) return na()
   return {sum: acc->sum + val, count: acc->count + 1}
 end

Also see reduce() which is easier to use if doing your own simple rollup computation.

foldCol (grid: Grid, colName: Str, fn: Func) => Obj?

Fold the values of the given column into a single value. The folding function uses the same semantics as fold.

Example:

readAll(site).foldCol("area", sum)

foldCols (grid: Grid, colSelector: Obj, newColName: Str, fn: Func) => Grid

Fold a set of columns in each row into a new folded column and return a new grid. The columns to fold are selected by the colSelector function and removed from the result. The selector may be a list of string names or a function which takes a Col and returns true to select it. The folding function uses same semantics as fold.

Example:

// consider grid 'g' with the following structure:
a    b    c
---  ---  ---
1    10   100
2    20   200

// foldCols, add b and c together to create new bc column
g.foldCols(["b", "c"], "bc", sum)

// yields this grid:
a    bc
---  ---
1    110
2    220

// we could also replace list of col names with a function
colSel: col => col.name == "b" or col.name == "c"
g.foldCols(colSel, "bc", sum)

foldStart () => Obj?

The fold start marker value

foldEnd () => Obj?

The fold end marker value

count (val: Obj, acc: Obj?) => Obj? <foldOn:Obj>

Fold multiple values into their total count Return zero if no values.

sum (val: Obj?, acc: Obj?) => Obj? <foldOn:Number>

Fold multiple values into their numeric sum. Return null if no values.

min (val: Obj?, acc: Obj?) => Obj? <foldOn:Number>

Compare two numbers and return the smaller one. This function may also be used with fold to return the smallest number (or null if no values). Note number units are not checked nor considered for this comparison.

Examples:

min(7, 4)            >>  4
[7, 2, 4].fold(min)  >>  2

max (val: Obj?, acc: Obj?) => Obj? <foldOn:Number>

Compare two numbers and return the larger one. This function may also be used with fold to return the largest number (or null if no values). Note number units are not checked nor considered for the comparison.

Examples:

max(7, 4)            >>  7
[7, 2, 4].fold(max)  >>  7

avg (val: Obj?, acc: Obj?) => Obj? <foldOn:Number>

Fold multiple values into their standard average or arithmetic mean. This function is the same as math::mean. Null values are ignored. Return null if no values.

Example:

[7, 2, 3].fold(avg)  >>  4

spread (val: Obj?, acc: Obj?) => Obj? <foldOn:Number>

Fold multiple values to compute the difference between the max and min value. Return null if no values.

Example:

[7, 2, 3].fold(spread)  >>  5

marker () => Marker

Get the marker value singleton Marker.val

none () => Obj

Get the none value singleton None.val

removeMarker () => Obj

This method is for backward compatibility only - use none().

na () => NA

Get NA not-available singleton NA.val

isTagName (n: Str) => Bool

Return if the given string is legal tag name - see Etc.isTagName

toTagName (n: Str) => Str

Given arbitrary string, convert to a safe tag name - see Etc.toTagName

names (dict: Dict) => Obj?

Get the list of names used by a given dict

vals (dict: Dict) => Obj?

Get the list of values used by a given dict

trap (val: Obj?, name: Str) => Obj?

Function for the -> operator. If the given value is a dict, then get a value by name, or throw UnknownNameErr if name not mapped. If the value is a Ref, then perform a checked readById, then perform the name lookup.

The trap function maybe be accessed using the -> shortcut operator:

 dict->foo  >>>  dict.trap("foo")

See Axon Language.

meta (val: Obj?) => Dict

Get the meta-data from a grid or col as a dict.

Examples:

read(temp).hisRead(today).meta             // grid meta
read(temp).hisRead(today).col("ts").meta   // column meta

cols (grid: Grid) => List

Get the columns from a grid as a list.

Example:

// get name of first column
readAll(site).cols.first.name

col (grid: Grid, name: Str, checked: Bool) => Obj?

Get a column by its name. If not resolved then return null or throw UnknownNameErr based on checked flag.

Example:

// get meta data for given columm
read(temp).hisRead(today).col("ts").meta

colNames (grid: Grid) => List

Get the column names a list of strings.

Example:

readAll(site).colNames

name (val: Obj?) => Str

If val is a Col, get the column name.

Example:

// get name of first column
readAll(site).cols.first.name

setMeta (grid: Obj, meta: Dict) => Obj

Return new grid with grid level meta-data replaced by given meta Dict. Also see addMeta and Streams.

Example:

read(temp).hisRead(today).setMeta({view:"table"})

addMeta (grid: Obj, meta: Dict) => Obj

Return new grid with additional grid level meta-data tags. Tags are added using merge conventions. Also see setMeta and Streams.

Example:

read(temp).hisRead(today).addMeta({view:"table"})

join (a: Grid, b: Grid, joinColName: Str) => Grid

Join two grids by column name. Current implementation requires:

  • grids cannot have conflicting col names (other than join col)
  • each row in both grids must have a unique value for join col
  • grid level meta is merged
  • join column meta is merged

joinAll (grids: List, joinColName: Str) => Grid

Join a list of grids into a single grid. See join.

addCol (grid: Grid, col: Obj?, fn: Func) => Grid

Add a column to a grid by mapping each row to a new cell value. The col parameter may be a simple String name or may be a dictionary which must have a "name" tag (any other tags become column meta-data). The mapping function takes (row) and returns the new cell values for the column.

Examples:

// add new column named areaMeter
readAll(site).addCol("areaMeters") s => s->area.to(1m²)

// add new column named areaMeter with dis meta
readAll(site).addCol({name:"areaMeters", dis:"Area Meters"}) s => s->area.to(1m²)

addCols (a: Grid, b: Grid) => Grid

Add grid b as a new set of columns to grid a. If b contains duplicate column names, then they are given auto-generated unique names. If b contains fewer rows then a, then the missing cells are filled with null.

Examples:

[{a:0, b:2}, {a:1, b:3}].toGrid.addCols({c:4}.toGrid)
readAll(rtu).addCols(readAll(meter))

renameCol (grid: Grid, oldName: Str, newName: Str) => Grid

Return a new grid with the given column renamed.

Example:

readAll(site).renameCol("dis", "title")

renameCols (grid: Grid, mapping: Dict) => Grid

Return a new grid with multiple columns renamed. Mapping must be a dict of old to new names. Old column names not found are ignored.

Example:

readAll(site).renameCols({dis:"title", geoAddr:"subtitle"})

reorderCols (grid: Obj, colNames: List) => Obj

Return a new grid with the columns reordered. The given list of names represents the new order and must contain the same current column names. Any columns not specified are removed. Also see colNames, moveTo, and Streams.

Example:

// move name to first col, and foo to last col
cols: grid.colNames.moveTo("name", 0).moveTo("foo", -1)
return grid.reorderCols(cols)

setColMeta (grid: Obj, name: Str, meta: Dict) => Obj

Return a new grid with column meta-data replaced by given meta dict. If column not found, then return given grid. Also see addColMeta and Streams.

addColMeta (grid: Obj, name: Str, meta: Dict) => Obj

Return a new grid with additional column meta-data. If column not found, then return given grid. Column meta is added using merge conventions. Also see setColMeta and Streams.

removeCol (grid: Obj, col: Obj) => Obj

Return a new grid with the given column removed. If the column doesn't exist, then return given grid. Also see Streams.

removeCols (grid: Obj, cols: List) => Obj

Return a new grid with all the given columns removed. Columns can be Str names or Col instances. Also see Streams.

keepCols (grid: Obj, cols: List) => Obj

Return a new grid with keeps the given columns, but removes all the others. Columns can be Str names or Col instances. Also see Streams.

Example:

readAll(site).keepCols(["id", "area"])

addRow (grid: Grid, newRow: Dict) => Grid

Add an additional Dict row to the end of a grid.

Example:

readAll(site).addRow({dis:"New Row"})

addRows (grid: Grid, newRows: Obj) => Grid

Add an list of rows to the end of a grid. The newRows may be expressed as list of Dict or a Grid.

Example:

readAll(site).addRows(readAll(equip))

rowToList (row: Obj) => List

Get a grid row as a list of cells. Sparse cells are included as null. Also see colToList().

Example:

readAll(equip).first.rowToList

colToList (grid: Grid, col: Obj) => List

Get a column as a list of the cell values ordered by row. Also see rowToList().

Example:

readAll(site).colToList("dis")

transpose (grid: Grid) => Grid

Perform a matrix transpose on the grid. The cells of the first column because the display names for the new columns. Columns 1..n become the new rows.

Example:

readAll(site).transpose

swizzleRefs (grid: Grid) => Grid

Given a grid of records, assign new ids and swizzle all internal ref tags. Each row of the grid must have an id tag. A new id is generated for each row, and any Ref tags which used one of the old ids is replaced with the new id. This function is handy for copying graphs of recs such as site/equip/point trees.

gridReplace (grid: Grid, from: Obj?, to: Obj?) => Grid

Replace every grid cell with the given from value with the to value. The resulting grid has the same grid and col meta. Replacement comparison is by via equality via == operator, so it will only replace scalar values or null.

Example:

grid.gridReplace(null, 0)   // replace all null cells with zero
grid.gridReplace(na(), 0)   // replace all NA cells with zero

times (times: Number, fn: Func) => Obj?

Call the specified function the given number of times passing the counter.

isOdd (val: Number) => Obj?

Return if an integer is an odd number.

isEven (val: Number) => Obj?

Return if an integer is an even number.

abs (val: Number?) => Obj?

Return absolute value of a number, if null return null

isNaN (val: Obj?) => Bool

Return if val is the Number representation of not-a-number

nan () => Number

Return the Number representation of not-a-number

posInf () => Number

Return the Number representation positive infinity

negInf () => Number

Return the Number representation negative infinity

clamp (val: Number, min: Number, max: Number) => Number

Clamp the number val between the min and max. If its less than min then return min, if its greater than max return max, otherwise return val itself. The min and max must have matching units or be unitless. The result is always in the same unit as val.

Examples:

14.clamp(10, 20)     >>   14    // is between 10 and 20
3.clamp(10, 20)      >>   10    // clamps to min 10
73.clamp(10, 20)     >>   20    // clamps to max 20
45°F.clamp(60, 80)   >>   60°F  // min/max can be unitless

today () => Date

Return today's Date according to context's time zone

yesterday () => Date

Return yesterday's Date according to context's time zone

now () => DateTime

Return current DateTime according to context's time zone. This function will use a cached version which is only accurate to within 250ms (see DateTime.now for details). Also see nowTicks() and nowUtc().

nowUtc () => DateTime

Return current DateTime in UTC. This function will use a cached version which is only accurate to within 250ms (see DateTime.nowUtc for details). Also see now() and nowTicks().

nowTicks () => Number

Return current time as nanosecond ticks since 1 Jan 2000 UTC. Note that the 64-bit floating point representations of nanosecond ticks will lose accuracy below the microsecond. Also see now().

occurred (ts: Obj?, range: Obj?) => Obj?

Return if a timestamp is contained within a Date range. Range may be any value supported by toDateSpan(). Timestamp may be either a Date or a DateTime. Also see contains().

Examples:

ts.occurred(thisWeek)
ts.occurred(pastMonth())
ts.occurred(2010-01-01..2010-01-15)

start (val: Obj?) => Obj?

Start value of a DateSpan, Span or a range.

end (val: Obj?) => Obj?

End value of a DateSpan, Span, or a range.

thisWeek () => Obj

DateSpan for this week as sun..sat (uses locale start of week)

thisMonth () => Obj

DateSpan for this month as 1st..28-31

thisQuarter () => Obj

DateSpan for this 3 month quarter

thisYear () => Obj

DateSpan for this year Jan-1..Dec-31

pastWeek () => Obj

DateSpan for last 7 days as today-7days..today

pastMonth () => Obj

DateSpan for last 30days today-30days..today

pastYear () => Obj

DateSpan for this past today-365days..today

lastWeek () => Obj

DateSpan for week previous to this week sun..sat (uses locale start of week)

lastMonth () => Obj

DateSpan for month previous to this month 1..28-31

lastQuarter () => Obj

DateSpan for 3 month quarter previous to this quarter

lastYear () => Obj

DateSpan for year previous to this year Jan-1..Dec-31

firstOfMonth (date: Date) => Date

Get the first day of given date's month. Also see lastOfMonth().

Example:

2009-10-28.firstOfMonth  >>  2009-10-01

lastOfMonth (date: Date) => Date

Get the last day of the date's month. Also see firstOfMonth().

Example:

2009-10-28.lastOfMonth  >>  2009-10-31

toDateSpan (x: Obj?) => Obj

Convert the following objects into a DateSpan:

  • Func: function which evaluates to date range
  • DateSpan: return itself
  • Date: one day range
  • Span: return Span.toDateSpan
  • Str: evaluates to DateSpan.fromStr
  • Date..Date: starting and ending date (inclusive)
  • Date..Number: starting date and num of days (day unit required)
  • DateTime..DateTime: use starting/ending dates; if end is midnight, then use previous date
  • Number: convert as year
  • null: use projMeta dateSpanDefault or default to today (deprecated)

Examples:

toDateSpan(2010-07-01..2010-07-03)  >>  01-Jul-2010..03-Jul-2010
toDateSpan(2010-07-01..60day)       >>  01-Jul-2010..29-Aug-2010
toDateSpan(2010-07)                 >>  01-Jul-2010..31-Jul-2010
toDateSpan(2010)                    >>  01-Jan-2010..31-Dec-2010
toDateSpan(pastWeek) // on 9 Aug    >>  02-Aug-2010..09-Aug-2010

toSpan (x: Obj?, tz: Str?) => Span

Convert the following objects into a Span:

  • Span: return itself
  • Span+tz: update timezone using same dates only if aligned to midnight
  • Str: return Span.fromStr using current timezone
  • Str+tz: return Span.fromStr using given timezone
  • DateTime..DateTime: range of two DateTimes
  • Date..DateTime: start day for date until the end timestamp
  • DateTime..Date: start timestamp to end of day for end date
  • DateTime: span of a single timestamp
  • DateSpan: anything accepted by toDateSpan in current timezone
  • DateSpan+tz: anything accepted by toDateSpan using given timezone

numDays (span: Obj?) => Number

Number of whole days in a span

eachDay (dates: Obj, fn: Func) => Obj?

Iterate the days of a span. The dates argument may be any object converted into a date range by toDateSpan. The given function is called with a Date argument for each iterated day.

Example:

f: day => echo(day)
eachDay(2010-07-01..2010-07-03, f) >> iterate Jul 1st, 2nd, 3rd
eachDay(2010-07, f)                >> iterate each day of July 2010
eachDay(pastWeek, f)               >> iterate last 7 days

eachMonth (dates: Obj, fn: Func) => Obj?

Iterate the months of a span. The dates argument may be any object converted into a date range by toDateSpan. The given function is called with a DateSpan argument for each interated month.

Examples:

// iterate each month in 2010, and echo data range
eachMonth(2010) d => echo(d)

// call f once for current method
eachMonth(today(), f)

year (d: Obj) => Obj?

Get year as integer such as 2010 from date or datetime

month (d: Obj) => Obj?

Get month as integer between 1 to 12 from date or datetime

day (d: Obj) => Obj?

Get day of month as integer between 1 to 31 from date or datetime.

hour (t: Obj) => Obj?

Get hour of day as integer between 0 to 23 from time or datetime

minute (t: Obj) => Obj?

Get minutes of the time as integer between 0 to 59 from time or datetime

second (t: Obj) => Obj?

Get seconds of the time as integer between 0 to 59 from time or datetime

weekday (t: Obj) => Number

Get weekday as integer from 0 to 6 of Date or DateTime. Zero indicates Sunday and 6 indicates Saturday

isWeekend (t: Obj) => Obj?

Does the given Date or DateTime fall on Sat or Sun

isWeekday (t: Obj) => Obj?

Does the given Date or DateTime fall on Mon, Tue, Wed, Thu, or Fri

tz (dt: DateTime?) => Obj?

Get timezone as city name string in tzinfo database from datetime. If the datetime is null then return the environment default timezone.

dateTime (d: Date, t: Time, tz: Str?) => Obj?

Construct a DateTime from a date, time, and timezone name. If timezone is null, use system default.

date (val: Obj, month: Number?, day: Number?) => Obj?

If val is a DateTime: get date portion of the timestamp. If val is a Number: construct a date instance from year, month, day

Examples:

now().date         // same as today()
date(2010, 12, 1)  // same as 2010-12-01

time (val: Obj, minutes: Number?, secs: Number) => Obj?

If val is a DateTime: get time portion of the timestamp. If val is a Number: construct a time instance from hour, minutes, secs (truncated to nearest second).

Examples:

now().time      // current time
time(20, 45)    // same as 20:45

toTimeZone (val: Obj, tz: Str) => Obj?

Convert a DateTime or Span to another timezone:

 now().toTimeZone("Chicago")
 now().toTimeZone("UTC")

numDaysInMonth (month: Obj?) => Number

Get the number of days in a given month. The month parameter may be:

  • Date: returns number of days in given month (uses month/year, ignores day)
  • Number 1-12: returns days in month for current year
  • null: returns day in current month

Examples:

numDaysInMonth()            >>>  days in current month
numDaysInMonth(1)           >>>  31day (days in January)
numDaysInMonth(6)           >>>  30day (days in June)
numDaysInMonth(2)           >>>  28day or 29day (days for Feb this year)
numDaysInMonth(2012-02-13)  >>>  29day (days in Feb for leap year)

isLeapYear (year: Number) => Bool

Return if a year is a leap year. Year must be four digit Number such as 2020.

dst (dt: DateTime) => Bool

Return if a DateTime is in daylight saving time. For the given DateTime and its specific timezone, return true if the time is in daylight savings time or false if standard time.

hoursInDay (dt: DateTime) => Number

Given a DateTime in a specific timezone, return the number of hours in the day. Dates which transition to DST will be 23 hours and days which transition back to standard time will be 25 hours.

dayOfYear (val: Obj) => Number

Given a DateTime or Date, return the day of the year. The result is a number between 1 and 365 (or 1 to 366 if a leap year).

weekOfYear (val: Obj, startOfWeek: Number?) => Number

Given a DateTime or Date, return the week number of the year. The result is a number between 1 and 53 using the given start of week weekday as number 0-6 (defaults start of week for current locale).

startOfWeek () => Number

Return current locale's start of weekday. Weekday is returned as integer from 0 (Sunday) to 6 (Saturday).

toJavaMillis (dt: DateTime) => Number

Given a DateTime return Number of milliseconds since Unix epoch. The epic is defined as 1-Jan-1970 UTC. Also see fromJavaMillis.

fromJavaMillis (millis: Number, tz: Str?) => DateTime

Given Number of milliseconds since Unix epoch return a DateTime. The epic is defined as 1-Jan-1970 UTC. If timezone is null, use system default. Also see toJavaMillis.

isMetric (val: Obj?) => Bool

Given an optional value return true if the SI metric system should be used. Return false if the United States customary unit system should be used. The following rules are used:

  • if val is a dict with geoCountry return return false if "US"
  • if number or rec with unit and unit is known to be a US customary unit return false (right now we only check for °F and Δ°F)
  • fallback to locale of hosting server, see Locale

Examples:

 isMetric({geoCountry:"US"})  >>  false
 isMetric({geoCountry:"FR"})  >>  true
 isMetric(75°F)               >>  false
 isMetric({unit:"Δ°C"})       >>  true
 isMetric()                   >>  fallback to server locale

unit (val: Number?) => Str?

Given a number return its unit string or null. If the val is null, then return null.

unitsEq (a: Number?, b: Number?) => Bool

Return if the two numbers have the same unit. If either of the numbers if null return false.

to (val: Number?, unit: Obj?) => Number?

Convert a number to the given unit. If the units are not of the same dimension then an exception is raised. The target unit can be a string or a Number. If target unit is a Number, then the scalar value is ignored, but by convention should be 1. Also see as() function to set a unit without conversion.

Examples:

 10kWh.to(1BTU)
 10kWh.to("BTU")
 75°F.to(1°C)
 to(75°F, 1°C)

as (val: Number?, unit: Obj?) => Number?

Set the unit of a number. Unlike to() function, no conversion of the scalar of the number is performed. The target unit can be a unit string or a number in which case the scalar value of the unit parameter is ignored (by convention should be 1).

Examples:

75°F.as(1°C)
75°F.as("°C")

def (symbol: Obj, checked: Bool) => Obj?

Lookup a def by its symbol name (Str or Symbol). If not found return null or raise UnknownDefErr based on checked flag. The result is returned as the definition's normalized dict representation.

defs () => List

List all definitions in the context namespace as Def[].

tags () => List

List tag definitions in the context namespace as Def[].

terms () => List

List term definitions (tags and conjuncts) in the context namespace as Def[].

conjuncts () => List

List conjunct definitions in the context namespace as Def[].

func (name: Obj, checked: Bool) => Dict?

Find a top-level function by name or by reference and return its tags. If not found throw exception or return null based on checked flag.

Example:

func("readAll")
func(readAll)

funcs (filter: Filter) => Grid

Find all the top-levels functions in the current project which match the given filter. If the filter is omitted then return all the functions declared in the current project. The function tags are returned.

Examples:

funcs()              // all functions
funcs(sparkRule)     // match filter

curFunc () => Dict

Get the current top-level function's tags.

is (val: Obj?, spec: Spec) => Bool

Return if the given instance inherits from the spec via nominal typing. Use specIs() to check nominal typing between two types. Also see fits() and specFits() to check via structural typing.

Note that dict values will only match the generic sys.Dict type. Use fits() for structural type matching.

Examples:

is("hi", Str)       >>  true
is("hi", Dict)      >>  false
is({}, Dict)        >>  true
is({equip}, Equip)  >>  false
is(Str, Spec)       >>  true

debugType (val: Obj?) => Str

Return a string of the given value's type. No guarantee is made for the string's format. Applications must not assume any specific format, this function is for human consumption only.

isNull (val: Obj?) => Bool

Return if an object is null

isNonNull (val: Obj?) => Bool

Return if an object is not null

isList (val: Obj?) => Bool

Return if an object is a list type

isDict (val: Obj?) => Bool

Return if an object is a dict type

isGrid (val: Obj?) => Bool

Return if an object is a grid type

isHisGrid (val: Obj?) => Bool

Return if an object is a grid that conforms to the history grid shape

isBool (val: Obj?) => Bool

Return if an object is a boolean type

isNumber (val: Obj?) => Bool

Return if an object is a number type

isDuration (val: Obj?) => Bool

Return if an object is a number type with a time unit

isRef (val: Obj?) => Bool

Return if an object is a ref type

isStr (val: Obj?) => Bool

Return if an object is a str type

isUri (val: Obj?) => Bool

Return if an object is a Uri type

isDate (val: Obj?) => Bool

Return if an object is a Date type

isTime (val: Obj?) => Bool

Return if an object is a Time type

isDateTime (val: Obj?) => Bool

Return if an object is a DateTime type

isFunc (val: Obj?) => Bool

Return if an object is a function type

isSpan (val: Obj?) => Bool

Return if an object is a span

isKeyword (val: Str) => Bool

Return if given string is an Axon keyword

toHex (val: Number) => Obj?

Convert a number to a hexadecimal string.

toRadix (val: Number, radix: Number, width: Number?) => Obj?

Convert a number to its string representation in the given radix (base). If width is non-null, then leading zeroes are prepended to ensure the specified width.

Example:

6.toRadix(2) => "110"
255.toRadix(16, 4) => "00ff"

toStr (val: Obj?) => Obj?

Convert an obj to its string representation

toList (val: Obj?) => List

If val is a list return it, otherwise return [val].

toGrid (val: Obj?, meta: Dict?) => Grid

Given an arbitrary object, translate it to a Grid via Etc.toGrid:

  • if grid just return it
  • if row in grid of size, return row.grid
  • if scalar return 1x1 grid
  • if dict return grid where dict is only
  • if list of dict return grid where each dict is row
  • if list of non-dicts, return one col grid with rows for each item

Example:

// create simple grid with dis,age cols and 3 rows:
[{dis:"Bob", age:30},
 {dis:"Ann", age:40},
 {dis:"Dan", age:50}].toGrid

colsToLocale (grid: Grid) => Grid

Localize column display names. For each col which does not have an explicit dislay name, add a dis tag based on the column name. Also see Grid.colsToLocale and hx.doc.skyspark::Localization#tags.

toLocale (key: Str) => Str

Get the localized string for the given tag name or qualified name. If the key is formatted as "pod::name" then route to Env.locale, otherwise to Etc.tagToLocale.

localeUse (locale: Str, expr: Obj?) => Obj?

Evaluate an expression within a specific locale. This enables formatting and parsing of localized text using a locale other than the default for the current context.

Examples:

// format Date in German
localeUse("de", today().format)

// parse Date in German
localeUse("de", parseDate("01 Mär 2021", "DD MMM YYYY"))

dis (dict: Dict?, name: Str?, def: Str) => Str

Get display string for dict or the given tag:

relDis (parent: Obj, child: Obj) => Str

Get a relative display name. If the child display name starts with the parent, then we can strip that as the common suffix. Parent and child must be either a Dict or a Str.

format (val: Obj?, pattern: Str?) => Str

Format an object using the current locale and specified format pattern. Formatting patterns follow Fantom toLocale conventions:

Examples:

 123.456kW.format                 >>  123kW
 123.456kW.format("#.0")          >>  123.5kW
 today().format("D-MMM-YYYY")     >>  8-Feb-2023
 today().format("DDD MMMM YYYY")  >>  8th February 2023
 now().format("D-MMM hh:mm")      >>  08-Feb 14:50
 now().format("DD/MM/YY k:mmaa")  >>  08/02/23 2:50pm

parseBool (val: Str, checked: Bool) => Bool?

Parse a Str into a Bool, legal formats are "true" or "false. If invalid format and checked is false return null, otherwise throw ParseErr.

Examples:

parseBool("true")
parseBool("bad", false)

parseInt (val: Str, radix: Number, checked: Bool) => Number?

Parse a Str into a integer number using the specified radix. If invalid format and checked is false return null, otherwise throw ParseErr. This string value cannot include a unit (see parseNumber).

Examples:

parseInt("123")
parseInt("afe8", 16)
parseInt("10010", 2)

parseFloat (val: Str, checked: Bool) => Number?

Parse a Str into a Float. Representations for infinity and not-a-number are "-INF", "INF", "NaN". If invalid format and checked is false return null, otherwise throw ParseErr. This string value cannot include a unit (see parseNumber).

Examples:

parseFloat("123.456").format("0.000")
parseFloat("NaN")
parseFloat("INF")

parseNumber (val: Str, checked: Bool) => Number?

Parse a Str into a number with an option unit. If invalid format and checked is false return null, otherwise throw ParseErr. Also see parseInt and parseFloat to parse basic integers and floating point numbers without a unit.

Examples:

 parseNumber("123")
 parseNumber("123kW")
 parseNumber("123.567").format("#.000")

parseUri (val: Str, checked: Bool) => Uri?

Parse a string into a Uri instance. If the string cannot be parsed into a valid Uri and checked is false then return null, otherwise throw ParseErr. This function converts an URI from standard form. Use uriDecode to convert a string from escaped form. See Uri for a detailed discussion on standard and escaped forms.

Examples:

"foo bar".parseUri     >>  `foo bar`
"foo%20bar".uriDecode  >>  `foo bar`

parseDate (val: Str, pattern: Str, checked: Bool) => Date?

Parse a Str into a Date. If the string cannot be parsed into a valid Date and checked is false then return null, otherwise throw ParseErr. See Date.toLocale for pattern.

Examples:

parseDate("7-Feb-23", "D-MMM-YY")
parseDate("07/02/23", "DD/MM/YY")
parseDate("7 february 2023", "D MMMM YYYY")
parseDate("230207", "YYMMDD")

parseTime (val: Str, pattern: Str, checked: Bool) => Time?

Parse a Str into a Time. If the string cannot be parsed into a valid Time and checked is false then return null, otherwise throw ParseErr. See Time.toLocale for pattern.

Examples:

parseTime("14:30", "h:mm")
parseTime("2:30pm", "k:mma")
parseTime("2:30:00pm", "k:mm:ssa")

parseDateTime (val: Str, pattern: Str, tz: Str, checked: Bool) => DateTime?

Parse a Str into a DateTime. If the string cannot be parsed into a valid DateTime and checked is false then return null, otherwise throw ParseErr. See DateTime.toLocale for pattern:

YY     Two digit year             07
YYYY   Four digit year            2007
M      One/two digit month        6, 11
MM     Two digit month            06, 11
MMM    Three letter abbr month    Jun, Nov
MMMM   Full month                 June, November
D      One/two digit day          5, 28
DD     Two digit day              05, 28
DDD    Day with suffix            1st, 2nd, 3rd, 24th
WWW    Three letter abbr weekday  Tue
WWWW   Full weekday               Tuesday
V      One/two digit week of year 1,52
VV     Two digit week of year     01,52
VVV    Week of year with suffix   1st,52nd
h      One digit 24 hour (0-23)   3, 22
hh     Two digit 24 hour (0-23)   03, 22
k      One digit 12 hour (1-12)   3, 11
kk     Two digit 12 hour (1-12)   03, 11
m      One digit minutes (0-59)   4, 45
mm     Two digit minutes (0-59)   04, 45
s      One digit seconds (0-59)   4, 45
ss     Two digit seconds (0-59)   04, 45
SS     Optional seconds (only if non-zero)
f*     Fractional secs trailing zeros
F*     Fractional secs no trailing zeros
a      Lower case a/p for am/pm   a, p
aa     Lower case am/pm           am, pm
A      Upper case A/P for am/pm   A, P
AA     Upper case AM/PM           AM, PM
z      Time zone offset           Z, +03:00 (ISO 8601, XML Schema)
zzz    Time zone abbr             EST, EDT
zzzz   Time zone name             New_York
'xyz'  Literal characters
''     Single quote literal

Examples:

parseDateTime("2023-02-07 14:30", "YYYY-MM-DD hh:mm")
parseDateTime("2023-02-07 14:30", "YYYY-MM-DD hh:mm", "Paris")
parseDateTime("7/2/23 2:30pm", "D/M/YY k:mma")
parseDateTime("2023-02-07T14:30:00", "YYYY-MM-DD'T'hh:mm:ss")

parseRef (val: Str, dis: Obj?, checked: Bool) => Ref?

Parse a Str into a Ref. If the string is not a valid Ref identifier then raise ParseErr or return null based on checked flag. If the string has a leading "@", then it is stripped off before parsing.

Examples:

parseRef("abc-123")
parseRef("@abc-123")

parseSymbol (val: Str, checked: Bool) => Obj?

Parse a Str into a Symbol. If the string is not a valid Symbol identifier then raise ParseErr or return null based on checked flag. The string must not include a leading "^".

Examples:

parseSymbol("func:now")

parseFilter (val: Str, checked: Bool) => Obj?

Parse a filter string into a Filter instance. The resulting filter can then be used with read(), readAll(), filter(), or filterToFunc().

Example:

str: "point and kw"
readAll(parseFilter(str))

parseSearch (val: Str) => Filter

Parse a search string into a Filter instance. The resulting filter can then be used with read(), readAll(), filter(), or filterToFunc().

The search string is one of the following free patterns:

  • *<glob>* case insensitive glob with ? and * wildcards (default)
  • re:<regex> regular expression
  • f:<filter> haystack filter

See hx.doc.fresco::Nav#searching for additional details on search syntax.

Examples:

readAll(parseSearch("RTU-1"))
readAll(point).filter(parseSearch("RTU* Fan"))

filterToFunc (filter: Filter) => Func

Convert a filter expression to a function which maybe used with findAll or find. The returned function accepts one Dict parameter and returns true/false if the Dict is matched by the filter. Also see filter() and parseFilter().

Examples:

// filter for dicts with 'equip' tag
list.findAll(filterToFunc(equip))

// filter rows with an 'area' tag over 10,000
grid.findAll(filterToFunc(area > 10_000))

parseUnit (val: Str, checked: Bool) => Str?

Parse a Str into a standardized unit name. If the val is not a valid unit name from the standard database then return null or raise exception based on checked flag.

Examples:

parseUnit("%")
parseUnit("percent")

xstr (type: Str, val: Str) => Obj

Construct decoded XStr instance

upper (val: Obj) => Obj?

Convert a char number or str to ASCII upper case. Also see lower() and capitalize().

Examples:

upper("cat")      >> "CAT"
upper("Cat")      >> "CAT"
upper(97).toChar  >> "A"

lower (val: Obj) => Obj?

Convert a char number or str to ASCII lower case. Also see upper() and decapitalize().

Examples:

lower("CAT")      >>  "cat"
lower("Cat")      >>  "cat"
lower(65).toChar  >>  "a"

isSpace (num: Number) => Bool

Is number is whitespace char: space \t \n \r \f

Examples:

isSpace("x".get(0))   >>  false
isSpace(" ".get(0))   >>  true
isSpace("\n".get(0))  >>  true

isAlpha (num: Number) => Bool

Is number an ASCII alpha char: isUpper||isLower

Examples:

isAlpha("A".get(0))  >>  true
isAlpha("a".get(0))  >>  true
isAlpha("8".get(0))  >>  false
isAlpha(" ".get(0))  >>  false
isAlpha("Ã".get(0))  >>  false

isAlphaNum (num: Number) => Bool

Is number an ASCII alpha-numeric char: isAlpha||isDigit

Examples:

isAlphaNum("A".get(0))  >>  true
isAlphaNum("a".get(0))  >>  true
isAlphaNum("8".get(0))  >>  true
isAlphaNum(" ".get(0))  >>  false
isAlphaNum("Ã".get(0))  >>  false

isUpper (num: Number) => Bool

Is number an ASCII uppercase alphabetic char: A-Z

Examples:

isUpper("A".get(0))  >>  true
isUpper("a".get(0))  >>  false
isUpper("5".get(0))  >>  false

isLower (num: Number) => Bool

Is number an ASCII lowercase alphabetic char: a-z

Examples:

isUpper("a".get(0))  >>  true
isUpper("A".get(0))  >>  false
isUpper("5".get(0))  >>  false

isDigit (num: Number, radix: Number) => Bool

Is number a digit in the specified radix. A decimal radix of ten returns true for 0-9. A radix of 16 also returns true for a-f and A-F.

Examples:

isDigit("5".get(0))      >>  true
isDigit("A".get(0))      >>  false
isDigit("A".get(0), 16)  >>  true

toChar (num: Number) => Str

Convert a unicode char number into a single char string

Examples:

toChar(65)   >>  "A"

split (val: Str, sep: Str?, opts: Dict?) => Obj?

Split a string by the given separator and trim whitespace. If sep is null then split by any whitespace char; otherwise it must be exactly one char long. See Str.split for detailed behavior.

Options:

  • noTrim: disable auto-trim of whitespace from start and end of tokens

Examples:

"a b c".split                   >>  ["a", "b", "c"]
"a,b,c".split(",")              >>  ["a", "b", "c"]
"a, b, c".split(",")            >>  ["a", "b", "c"]
"a, b, c".split(",", {noTrim})  >>  ["a", " b", " c"]

capitalize (val: Str) => Str

Return this string with the first character converted to uppercase. The case conversion is for ASCII only. Also see decapitalize() and upper().

Examples:

capitalize("apple")  >>  "Apple"

decapitalize (val: Str) => Str

Return this string with the first character converted to lowercase. The case conversion is for ASCII only. Also see capitalize() and lower().

Examples:

decapitalize("Apple") >> "apple"

trim (val: Str) => Str

Trim whitespace from the beginning and end of the string. For the purposes of this function, whitespace is defined as any character equal to or less than the 0x20 space character (including , \r, \n, and \t).

Examples:

" abc ".trim   >>  "abc"
"abc".trim     >>  "abc"

trimStart (val: Str) => Str

Trim whitespace only from the beginning of the string. See trim for definition of whitespace.

Examples:

" abc ".trimStart  >>  "abc "
"abc".trimStart    >>  "abc"

trimEnd (val: Str) => Str

Trim whitespace only from the end of the string. See trim for definition of whitespace.

Examples:

" abc ".trimEnd  >>  " abc"
"abc".trimEnd    >>  "abc"

startsWith (val: Str, sub: Str) => Bool

Return if Str starts with the specified Str.

Examples:

"hi there".startsWith("hi")   >>  true
"hi there".startsWith("foo")  >>  false

endsWith (val: Str, sub: Str) => Bool

Return if Str ends with the specified Str.

Examples:

"hi there".endsWith("there")   >>  true
"hi there".endsWith("hi")      >>  false

replace (val: Str, from: Str, to: Str) => Str

String replace of all occurrences of from with to. All three parameters must be strings.

Examples:

"hello".replace("hell", "t")  >>  "to"
"aababa".replace("ab", "-")   >>  "a--a"

padl (val: Str, width: Number, char: Str) => Str

Pad string to the left. If size is less than width, then add the given char to the left to achieve the specified width.

Examples:

"3".padl(3, "0")    >>  "003"
"123".padl(2, "0")  >>  "123"

padr (val: Str, width: Number, char: Str) => Str

Pad string to the right. If size is less than width, then add the given char to the left to acheive the specified with.

Examples:

"xyz".padr(2, ".")  >>  "xyz"
"xyz".padr(5, "-")  >>  "xyz--"

concat (list: List, sep: Str) => Str

Concatenate a list of items into a string.

Examples:

[1, 2, 3].concat       >>  "123"
[1, 2, 3].concat(",")  >>  "1,2,3"

reMatches (regex: Obj, s: Str) => Bool

Return if regular expression matches entire region of s. See AxonUsage.

Examples:

reMatches(r"\d+", "x123y")  >>  false
reMatches(r"\d+", "123")    >>  true

reFind (regex: Obj, s: Str) => Str?

Find the first match of regular expression in s or return null if no matches. See AxonUsage.

Examples:

reFind(r"\d+", "x123y")  >>  "123"
reFind(r"\d+", "xyz")    >>  null

reFindAll (regex: Obj, s: Str) => List

Find all matches of the regular expression in s. Returns an empty list of there are no matches.

Examples:

reFindAll(r"-?\d+\.?\d*", "foo, 123, bar, 456.78, -9, baz")
  >> ["123", "456.78", "-9"]
reFindAll(r"\d+", "foo, bar, baz")
  >> [,]

reGroups (regex: Obj, s: Str) => Obj?

Return a list of the substrings captured by matching the given regular operation against s. Return null if no matches. The first item in the list is the entire match, and each additional item is matched to () arguments in the regex pattern. See AxonUsage.

Examples:

re: r"(RTU|AHU)-(\d+)"
reGroups(re, "AHU")    >> null
reGroups(re, "AHU-7")  >> ["AHU-7", "AHU", "7"]

uriScheme (val: Uri) => Str?

Get the scheme of a Uri as a string or null

uriHost (val: Uri) => Str?

Get the host Uri as a string or null

uriPort (val: Uri) => Number?

Get the port of a Uri as a Number or null

uriName (val: Uri) => Str?

Get the name Str of a Uri (last item in path).

uriPath (val: Uri) => Obj?

Get the path segments of a Uri as a list of Strs.

uriPathStr (val: Uri) => Str?

Get the path a Uri as a string.

uriBasename (val: Uri) => Str?

Get the basename (last name in path without extension) of a Uri as a string.

uriExt (val: Uri) => Str?

Get the URI extension of a Uri as a string or null.

uriIsDir (val: Uri) => Bool

Return if the URI path ends in a slash.

uriFrag (val: Uri) => Str?

Return if the fragment identifier portion of the a URI after hash symbol

uriQueryStr (val: Uri) => Str?

Return if the query portion of the a URI after question mark

uriPlusSlash (val: Uri) => Uri

Adding trailing slash to the URI. See Uri.plusSlash

uriEncode (val: Uri) => Str

Return the percent encoded string for this Uri according to RFC 3986. Each section of the Uri is UTF-8 encoded into octects and then percent encoded according to its valid character set. Spaces in the query section are encoded as +.

Examples:

`foo bar`.uriEncode  >>  "foo%20bar"

uriDecode (val: Str, checked: Bool) => Uri

Parse an ASCII percent encoded string into a Uri according to RFC 3986. All %HH escape sequences are translated into octects, and then the octect sequence is UTF-8 decoded into a Str. The + character in the query section is unescaped into a space. If checked if true then throw ParseErr if the string is a malformed URI or if not encoded correctly, otherwise return null. Use parseUri to parse from standard form. See Uri for a detailed discussion on standard and encoded forms.

Examples:

"foo bar".parseUri     >>  `foo bar`
"foo%20bar".uriDecode  >>  `foo bar`

refGen () => Ref

Generate a new unique Ref identifier

refDis (ref: Ref) => Str

Given a ref return Ref.dis

refProjName (ref: Ref, checked: Bool) => Str?

Given an absolute ref, return its project name. If the ref is not formatted as "p:proj:r:xxx", then raise an exception or return null based on the checked flag:

Examples:

 refProjName(@p:demo:r:xxx)   >>  "demo"
 refProjName(@r:xxx)          >>  raises exception
 refProjName(@r:xxx, false)   >>  null

coord (lat: Number, lng: Number) => Obj

Construct a Coord from two Numbers in decimal degrees

coordLat (coord: Obj) => Number

Latitude of a Coord as a Number

coordLng (coord: Obj) => Number

Longitude of a Coord as a Number

coordDist (c1: Obj, c2: Obj) => Number

Compute the great-circle distance between two Coords. The result is a distance in meters using the haversine forumula.

echo (x: Obj?) => Obj? <admin>

Write the str represenation of x to stdout and return x.

eval (expr: Str) => Obj?

Evaluate an Axon string expression. The evaluation happens in a new scope and does not have access to the current scope of local variables. Also see call() and toAxonCode().

Examples:

eval("2 + 2")
eval("now()")

evalToFunc (expr: Str) => Func

Evalate an Axon string expression to a function. Typically the expression is just a function name, but it can be any expression that evaluates to a function. Raise an exception if the expression does not evaluate to a function. Note this call does evalute the given expression in the runtime, so it must be used with caution - never use it with a string from a non-trusted origin.

Examples:

evalToFunc("now").call
evalToFunc("(x, y)=>x+y").call([3, 4])
(evalToFunc("(x, y)=>x+y"))(3, 4)
evalToFunc("""replace(_, "x", "_")""").call(["xyz"])

call (func: Obj, args: List?) => Obj?

Reflectively call a function with the given arguments. The func may be a Str name or an expression that evaluates to a function. Args is a positional list for each argument. Examples:

call("today")
call("replace", ["hi there", "hi", "hello"])
call("parseDate", ["2021-03-15"])
call("parseDate", ["15-Mar-21", "DD-MMM-YY"])
call(parseDate, ["15-Mar-21", "DD-MMM-YY"])
call(parseDate(_, "DD-MMM-YY"), ["15-Mar-21"])

callByName (func: Obj, args: Dict) => Obj?

Reflectively call a function with arguments by name. The func may be a Str name or an expression that evaluates to a function. Args a dict with the arguments keyed by name. Note that null might indicate an actual null argument or a fallback to a default value. So any arguments are null, the pass a value for argument. Examples:

callByName("parseDate", {val:"01-02-03", pattern:"DD-MM-YY"})
callByName(parseDate, {val:"01-02-03", pattern:"DD-MM-YY"})

Note that parameter names might change between releases.

toAxonCode (val: Obj?) => Obj?

Convert a scalar, list, or dict value to its Axon code representation. Examples:

toAxonCode(123)        =>   "123"
toAxonCode([1, 2, 3])  =>   "[1, 2, 3]"
toAxonCode({x:123})    =>   "{x:123}"

parseAst (src: Str) => Dict

Parse Axon source code into an abstract syntax tree modeled as a tree of dicts. Each node has a type tag which specified the node type. Common AST shapes:

 123    =>  {type:"literal", val:123}
 a      =>  {type:"var", name:"a"}
 not a  =>  {type:"not", operand:{type:"var", name:"a"}}
 a + b  =>  {type:"add", lhs:{type:"var", name:"a"}, rhs:{type:"var", name:"b"}}

NOTE: the keys and structure of the AST is subject to change over time.

Haxall 4.0.5 ∙ 24-Feb-2026 14:33 EST