From 757ddd24d9c4b34d0fc6b619819362da0856f2d4 Mon Sep 17 00:00:00 2001 From: Muqiu Han Date: Mon, 11 Mar 2024 12:00:13 +0800 Subject: [PATCH] Add reverse function to stack module --- stack/stack.mbt | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/stack/stack.mbt b/stack/stack.mbt index a84f57e11..28964345c 100644 --- a/stack/stack.mbt +++ b/stack/stack.mbt @@ -585,6 +585,29 @@ test "forall" { )? } +/// Checks if all elements of the list satisfy the predicate f. +/// If the list is empty, return true. +/// +/// NOTE: Since the current standard library List lacks the forall function, +/// this function internally implements the forall function of List. +/// +/// # Example +/// +/// ``` +/// println(Stack::[2, 4, 6].reverse()) +/// // output: Cons(2, Cons(4, Cons(6, Nil))) +/// ``` +pub fn reverse[T](self : Stack[T]) -> Stack[T] { + { elements: self.elements.reverse(), len: self.len } +} + +test "reverse" { + @assertion.assert_eq( + Stack::[2, 4, 6].reverse().elements, + Cons(2, Cons(4, Cons(6, Nil))), + )? +} + /// Compare two stacks. /// /// NOTE: Since the current standard library List lacks the equal or op_equal function,