Skip to content

Commit

Permalink
Merge pull request #3082 from tokiwa-software/x.abs_as_|x|
Browse files Browse the repository at this point in the history
lib: add prefix and postfix operators for `|x|` instead of `x.abs`
  • Loading branch information
fridis committed May 21, 2024
2 parents 4d44eec + 6157aeb commit 2600b32
Show file tree
Hide file tree
Showing 3 changed files with 124 additions and 2 deletions.
38 changes: 36 additions & 2 deletions lib/numeric.fz
Original file line number Diff line number Diff line change
Expand Up @@ -119,9 +119,43 @@ module:public numeric : property.hashable, property.orderable is
=> abstract


public sign => if numeric.this = numeric.this.zero then 0 else if numeric.this > numeric.this.zero then 1 else -1
# sign function resulting in `-1`/`0`/`+1` depending on whether `numeric.this`
# is less than, equal or larger than zero
#
public sign =>
if numeric.this = numeric.this.zero then 0
else if numeric.this > numeric.this.zero then 1
else -1


# absolute value
#
public abs =>
if sign ≥ 0 then numeric.this
else -numeric.this


# absolute value using `|a|` built from a `prefix |` and `postfix |` as an operator
# alias of `a.abs`
#
# Due to the low precedence of `|`, this works also on expressions like `|a-b|`, even
# with spaces `| a-b |`, `|a - b|`, `| a-b|` or `|a-b |`.
#
# Nesting, however, does not work, e.g, `| - |a| |`, this requires parenthese `|(- |a|)|`.
#
# NYI: CLEANUP: Due to #3081, we need `postfix |` as the first operation, should be
# `prefix |` first
#
public postfix | is

# only useful operation is the corresponding `prefix |`
#
public prefix | => numeric.this.abs

public abs => if sign ≥ 0 then numeric.this else -numeric.this
# redefine as_string to try to explain what is wrong if only one `|` is used
#
public redef as_string =>
"*** numeric.postfix |, requires corresponding prefix | for abs value ***"


# does this numeric value fit into an u8? This is redefined by children
Expand Down
2 changes: 2 additions & 0 deletions tests/basicIntegers/basicIntegers.fz
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ basicIntegers =>
if !b.is_zero
say "{T.name}: $a / $b = {a / b}"
say "{T.name}: $a % $b = {a % b}"
if a -! b
say "{T.name}: |$a - $b| = {|a-b|}"

test_i64 (a, b i64) unit => test i64 a b
test_i32 (a, b i64) unit => test i32 a.low32bits.cast_to_i32 b.low32bits.cast_to_i32
Expand Down

0 comments on commit 2600b32

Please sign in to comment.