diff --git a/docs/content/manual/manual.yml b/docs/content/manual/manual.yml index d629900f6b..8ad8029f67 100644 --- a/docs/content/manual/manual.yml +++ b/docs/content/manual/manual.yml @@ -854,6 +854,21 @@ sections: input: '[1,0,-1]' output: ['1', '-1'] + - title: "`abs`" + body: | + + The builtin function `abs` is defined naively as: `if . < 0 then - . else . end`. + + For numeric input, this is the absolute value. See the + section on the identity filter for the implications of this + definition for numeric input. + + To compute the absolute value of a number as a floating point number, you may wish use `fabs`. + + examples: + - program: 'map(abs)' + input: '[-10, -1.1, -1e-1]' + output: ['[10,1.1,1e-1]'] - title: "`length`" body: | diff --git a/jq.1.prebuilt b/jq.1.prebuilt index e7d1a972c3..c72fad2ca7 100644 --- a/jq.1.prebuilt +++ b/jq.1.prebuilt @@ -838,6 +838,27 @@ jq \'\.[] | (1 / \.)?\' . .IP "" 0 . +.SS "abs" +The builtin function \fBabs\fR is defined naively as: \fBif \. < 0 then \- \. else \. end\fR\. +. +.P +For numeric input, this is the absolute value\. See the section on the identity filter for the implications of this definition for numeric input\. +. +.P +To compute the absolute value of a number as a floating point number, you may wish use \fBfabs\fR\. +. +.IP "" 4 +. +.nf + +jq \'map(abs)\' + [\-10, \-1\.1, \-1e\-1] +=> [10,1\.1,1e\-1] +. +.fi +. +.IP "" 0 +. .SS "length" The builtin function \fBlength\fR gets the length of various different types of value: . diff --git a/src/builtin.jq b/src/builtin.jq index 45ba3060a3..e74e9771dc 100644 --- a/src/builtin.jq +++ b/src/builtin.jq @@ -10,6 +10,7 @@ def max_by(f): _max_by_impl(map([f])); def min_by(f): _min_by_impl(map([f])); def add: reduce .[] as $x (null; . + $x); def del(f): delpaths([path(f)]); +def abs: if . < 0 then - . else . end; def _assign(paths; $value): reduce path(paths) as $p (.; setpath($p; $value)); def _modify(paths; update): reduce path(paths) as $p ([., []]; diff --git a/tests/jq.test b/tests/jq.test index 466d185099..c617055669 100644 --- a/tests/jq.test +++ b/tests/jq.test @@ -1808,6 +1808,23 @@ false 1 1 +# abs, fabs, length +abs +"abc" +"abc" + +map(abs) +[-0, 0, -10, -1.1] +[0,0,10,1.1] + +map(fabs == length) | unique +[-10, -1.1, -1e-1, 1000000000000000002] +[true] + +# The following is NOT prescriptive: +map(abs) +[0.1,1000000000000000002] +[1e-1, 1000000000000000002] # Using a keyword as variable/label name diff --git a/tests/man.test b/tests/man.test index cce2edb3f8..354043ba67 100644 --- a/tests/man.test +++ b/tests/man.test @@ -188,6 +188,10 @@ null 1 -1 +map(abs) +[-10, -1.1, -1e-1] +[10,1.1,1e-1] + .[] | length [[1,2], "string", {"a":2}, null, -5] 2