Skip to content

Commit

Permalink
feat: ref.incr() and ref.decr()
Browse files Browse the repository at this point in the history
  • Loading branch information
Yoorkin authored and lijunchen committed Mar 15, 2024
1 parent 99c750f commit 6c41d13
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
4 changes: 3 additions & 1 deletion ref/moon.pkg.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
{
"import": [
{ "path": "moonbitlang/core/assertion", "alias": "assertion" }
"moonbitlang/core/assertion",
"moonbitlang/core/num",
"moonbitlang/core/int"
]
}
32 changes: 32 additions & 0 deletions ref/ref.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -101,3 +101,35 @@ test "swap" {
pub fn update[T](self : Ref[T], f : (T) -> T) {
self.val = f(self.val)
}

/// Increments the value of a reference by 1. The default value is 1.
pub fn incr[T : @num.Num](
self : Ref[T],
~value : T = @num.Num::from_int(1)
) -> Unit {
self.val = self.val + value
}

/// Decrements the value of a reference by value. The default value is 1.
pub fn decr[T : @num.Num](
self : Ref[T],
~value : T = @num.Num::from_int(1)
) -> Unit {
self.val = self.val - value
}

test "decr" {
let a = ref(1)
a.decr()
@assertion.assert_eq(a.val, 0)?
a.decr(~value=5)
@assertion.assert_eq(a.val, -5)?
}

test "incr" {
let a = ref(1)
a.incr()
@assertion.assert_eq(a.val, 2)?
a.incr(~value=5)
@assertion.assert_eq(a.val, 7)?
}

0 comments on commit 6c41d13

Please sign in to comment.