summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorStephen Dolan <mu@netsoc.tcd.ie>2013-09-14 16:34:52 -0700
committerStephen Dolan <mu@netsoc.tcd.ie>2013-09-14 16:34:52 -0700
commit4e3024cb6149cd04f04c5471c35712411a12bde2 (patch)
tree22df16a76f733aa50dafa370808602d710965d41
parentdae2422fd18487c89dd79dc54eb4345861ab7bdc (diff)
parentc427bf6a94fb026e8105edc2210dfde0e98c00c2 (diff)
Merge pull request #182 from mdaines/sqrt-builtin
Add builtin for calculating square root
-rw-r--r--builtin.c11
-rw-r--r--docs/content/3.manual/manual.yml10
-rw-r--r--tests/all.test8
3 files changed, 29 insertions, 0 deletions
diff --git a/builtin.c b/builtin.c
index a61e8204..721cd3fc 100644
--- a/builtin.c
+++ b/builtin.c
@@ -59,6 +59,15 @@ static jv f_floor(jv input) {
return ret;
}
+static jv f_sqrt(jv input) {
+ if (jv_get_kind(input) != JV_KIND_NUMBER) {
+ return type_error(input, "has no square root");
+ }
+ jv ret = jv_number(sqrt(jv_number_value(input)));
+ jv_free(input);
+ return ret;
+}
+
static jv f_negate(jv input) {
if (jv_get_kind(input) != JV_KIND_NUMBER) {
return type_error(input, "cannot be negated");
@@ -474,6 +483,7 @@ static jv f_error(jv input, jv msg) {
static const struct cfunction function_list[] = {
{(cfunction_ptr)f_floor, "_floor", 1},
+ {(cfunction_ptr)f_sqrt, "_sqrt", 1},
{(cfunction_ptr)f_plus, "_plus", 3},
{(cfunction_ptr)f_negate, "_negate", 1},
{(cfunction_ptr)f_minus, "_minus", 3},
@@ -559,6 +569,7 @@ static const char* const jq_builtins[] = {
"def max_by(f): _max_by_impl(map([f]));",
"def min_by(f): _min_by_impl(map([f]));",
"def floor: _floor;",
+ "def sqrt: _sqrt;",
"def add: reduce .[] as $x (null; . + $x);",
"def del(f): delpaths([path(f)]);",
"def _assign(paths; value): value as $v | reduce path(paths) as $p (.; setpath($p; $v));",
diff --git a/docs/content/3.manual/manual.yml b/docs/content/3.manual/manual.yml
index 26779549..6fb83940 100644
--- a/docs/content/3.manual/manual.yml
+++ b/docs/content/3.manual/manual.yml
@@ -633,6 +633,16 @@ sections:
input: '3.14159'
output: ['3']
+ - title: `sqrt`
+ body: |
+
+ The `sqrt` function returns the square root of its numeric input.
+
+ examples:
+ - program: 'sqrt'
+ input: '9'
+ output: ['3']
+
- title: `tonumber`
body: |
diff --git a/tests/all.test b/tests/all.test
index af6f8a1c..c16b7eba 100644
--- a/tests/all.test
+++ b/tests/all.test
@@ -366,6 +366,14 @@ null
[-1.1,1.1,1.9]
[-2, 1, 1]
+[.[]|sqrt]
+[4,9]
+[2,3]
+
+(add / length) as $m | map((. - $m) as $d | $d * $d) | add / length | sqrt
+[2,4,4,4,5,5,7,9]
+2
+
def f(x): x | x; f([.], . + [42])
[1,2,3]
[[[1,2,3]]]