From 82ad57901bb43c6beb349ba9be15b2d464b8cb46 Mon Sep 17 00:00:00 2001 From: Ziyang Hu Date: Fri, 2 Sep 2022 20:05:15 +0800 Subject: [PATCH] reverse --- docs/functions.md | 2 ++ src/data/expr.rs | 1 + src/data/functions.rs | 10 ++++++++++ src/data/tests/functions.rs | 17 ++++++++++++++++- 4 files changed, 29 insertions(+), 1 deletion(-) diff --git a/docs/functions.md b/docs/functions.md index ad85ea28..af8cc58d 100644 --- a/docs/functions.md +++ b/docs/functions.md @@ -124,6 +124,8 @@ The four _basic arithmetic operators_ `+`, `-`, `*`, and `/` do what you expect, `prepend(l, x)`, `append(l, x)`: prepends / appends the element `x` to the list `l`. +`reverse(l)` reverses the list. + `sorted(l)`: returns the sorted list as defined by the total order detailed in [datatypes](datatypes.md). `chunks(l, n)`: splits the list `l` into chunks of `n`, e.g. `chunks([1, 2, 3, 4, 5], 2) == [[1, 2], [3, 4], [5]]`. diff --git a/src/data/expr.rs b/src/data/expr.rs index e7dc6daf..a3095a6b 100644 --- a/src/data/expr.rs +++ b/src/data/expr.rs @@ -431,6 +431,7 @@ pub(crate) fn get_op(name: &str) -> Option<&'static Op> { "is_nan" => &OP_IS_NAN, "length" => &OP_LENGTH, "sorted" => &OP_SORTED, + "reverse" => &OP_REVERSE, "append" => &OP_APPEND, "prepend" => &OP_PREPEND, "unicode_normalize" => &OP_UNICODE_NORMALIZE, diff --git a/src/data/functions.rs b/src/data/functions.rs index c02849a3..768a64bc 100644 --- a/src/data/functions.rs +++ b/src/data/functions.rs @@ -978,6 +978,16 @@ pub(crate) fn op_sorted(args: &[DataValue]) -> Result { Ok(DataValue::List(arg)) } +define_op!(OP_REVERSE, 1, false); +pub(crate) fn op_reverse(args: &[DataValue]) -> Result { + let mut arg = args[0] + .get_list() + .ok_or_else(|| anyhow!("cannot apply 'reverse' to {:?}", args))? + .to_vec(); + arg.reverse(); + Ok(DataValue::List(arg)) +} + define_op!(OP_HAVERSINE, 4, false); pub(crate) fn op_haversine(args: &[DataValue]) -> Result { let gen_err = || anyhow!("cannot computer haversine distance for {:?}", args); diff --git a/src/data/tests/functions.rs b/src/data/tests/functions.rs index a60bb153..d75b38fd 100644 --- a/src/data/tests/functions.rs +++ b/src/data/tests/functions.rs @@ -932,7 +932,7 @@ fn test_unicode_normalize() { } #[test] -fn test_sort() { +fn test_sort_reverse() { assert_eq!( op_sorted(&[DataValue::List(vec![ DataValue::from(2.0), @@ -947,6 +947,21 @@ fn test_sort() { DataValue::from(2), DataValue::from(2.0), ]) + ); + assert_eq!( + op_reverse(&[DataValue::List(vec![ + DataValue::from(2.0), + DataValue::from(1), + DataValue::from(2), + DataValue::Null + ])]) + .unwrap(), + DataValue::List(vec![ + DataValue::Null, + DataValue::from(2), + DataValue::from(1), + DataValue::from(2.0), + ]) ) }