Skip to content

Commit

Permalink
Fix seq->openArray and int->SomeInteger
Browse files Browse the repository at this point in the history
  • Loading branch information
dlesnoff committed Mar 17, 2023
1 parent f11230c commit 74ec13a
Showing 1 changed file with 15 additions and 12 deletions.
27 changes: 15 additions & 12 deletions maths/abs.nim
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,14 @@ runnableExamples:
doAssert absMaxSort(@[3, -10, -2]) == -10

func absVal[T: SomeFloat](num: T): T =
## Returns the absolute value of a number.
## Use `math.abs <https://nim-lang.org/docs/system.html#abs%2CT>`_ instead!
## Returns the absolute value of a number.
## Use `math.abs <https://nim-lang.org/docs/system.html#abs%2CT>`_ instead!
return if num < 0.0: -num else: num

# Same for integers but return a Natural
func absVal(num: int): Natural = (if num < 0: -num else: num)
# Same for Integers but returns a Natural
func absVal[T: SomeInteger](num: T): Natural = (if num < 0: -num else: num)

func absMin(x: seq[int]): Natural {.raises: [ValueError].} =
func absMin(x: openArray[int]): Natural {.raises: [ValueError].} =
## Returns the smallest element in absolute value in a sequence.
if x.len == 0:
raise newException(ValueError, "Cannot find absolute minimum of an empty sequence")
Expand All @@ -25,7 +25,7 @@ func absMin(x: seq[int]): Natural {.raises: [ValueError].} =
if absVal(x[i]) < result:
result = absVal(x[i])

func absMax(x: seq[int]): Natural {.raises: [ValueError].} =
func absMax(x: openArray[int]): Natural {.raises: [ValueError].} =
## Returns the largest element in absolute value in a sequence.
if x.len == 0:
raise newException(ValueError, "Cannot find absolute maximum of an empty sequence")
Expand Down Expand Up @@ -61,28 +61,31 @@ when isMainModule:
absMin(@[-1, 2, -3]) == 1
absMin(@[0, 5, 1, 11]) == 0
absMin(@[3, -10, -2]) == 2

absMin([-1, 2, -3]) == 1
absMin([0, 5, 1, 11]) == 0
absMin([3, -10, -2]) == 2

test "`absMin` on empty sequence raises ValueError":
doAssertRaises(ValueError):
discard absMin(@[])

suite "Check `absMax`":
test "Check `absMax`":
check:
absMax(@[0, 5, 1, 11]) == 11
absMax(@[3, -10, -2]) == 10
absMax(@[-1, 2, -3]) == 3

test "`absMax` on empty sequence raises ValueError":
doAssertRaises(ValueError):
discard absMax(@[])

suite "Check `absMaxSort`":
test "Check `absMaxSort`":
check:
absMaxSort(@[3, -2, 1, -4, 5, -6]) == -6
absMaxSort(@[0, 5, 1, 11]) == 11

test "`absMaxSort` on empty sequence raises ValueError":
doAssertRaises(ValueError):
discard absMaxSort(@[])
discard absMaxSort(@[])

0 comments on commit 74ec13a

Please sign in to comment.