Skip to content

Instantly share code, notes, and snippets.

@leveled
Created February 3, 2021 13:28
Show Gist options
  • Save leveled/e49184c53febd43f19919df771622521 to your computer and use it in GitHub Desktop.
Save leveled/e49184c53febd43f19919df771622521 to your computer and use it in GitHub Desktop.
Procedures in Nim
#Procedure with implicit return result
proc sumTillNegative(x: varargs[int]): int =
for i in x:
if i < 0:
return
result = result + i
echo sumTillNegative() # echos 0
echo sumTillNegative(3, 4, 5) # echos 12
echo sumTillNegative(3, 4 , -1 , 6) # echos 7
#Procedure with mutable variable
proc divmod(a, b: int; res, remainder: var int) =
res = a div b # integer division
remainder = a mod b # integer modulo operation
var
x, y: int
divmod(8, 5, x, y) # modifies x and y
echo x
echo y
#ignoring return value
discard yes("May I ask a pointless question?")
proc p(x, y: int): int {.discardable.} =
return x + y
p(3, 4) # now valid
#Procedure with named arguments and default values
proc createWindow(x = 0, y = 0, width = 500, height = 700,
title = "unknown",
show = true): Window =
...
var w = createWindow(title = "My Application", height = 600, width = 800)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment