Last active
July 23, 2019 03:03
-
-
Save juancarlospaco/278a9a8106c9c1b48abaa2f9612174e8 to your computer and use it in GitHub Desktop.
Python Vs Nim: Functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# args are immutable by default. | |
# Variables immutables by default (std lib). | |
# func ensures exampleFunction dont have Side Effects (is a Functional function). | |
func exampleFunction(arg: Natural): range[0..100] = # Static Types no type Bugs possible (wont compile otherwise). range[0..100] only allows integers from 0 to 100. Natural only allows integers not Negative (>=0). | |
# result variable is automatically created for you (you always need to return a result anyways) | |
preconditions arg > 0, arg < 101 # Preconditions (like a Unittest BEFORE a block of code, asserts on args and variables) | |
postconditions result > 0, result < 101 # Postconditions (like a Unittest AFTER a block of code, asserts on result) | |
result = arg + 1 # Mimic some logic here, it does not really matter for this example | |
# result is automatically returned, no need for "return result" (can still use return if wanted tho) | |
# guarantee result is integer between 0 and 100, Bugs very unlikely (wont compile otherwise). |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import namedtuple | |
# args are mutable by default. | |
# No way to make variables immutables with std lib. | |
# No way to ensure exampleFunction dont have Side Effects reliably. | |
def exampleFunction(arg: int) -> int: # Type hints but still Bugs happen (Not as good as real static types). No way to enforce a range of integer between 0 and 100. | |
result = 0 # Predefined result variable (better to assert and debug everywhere on the body of the function, if you dont start with a predefined result on Python it can return None, anything can be None then you dont know what happened on the function, and you always need to return a result anyways) | |
assert arg > 0 # Preconditions (no better way on Python) | |
assert arg < 101 # Preconditions (no better way on Python) | |
result = arg + 1 # Mimic some logic here, it does not really matter for this example | |
assert result > 0 # Postconditions (no better way on Python) | |
assert result < 101 # Postconditions (no better way on Python) | |
return namedtuple("result", "result")(result) # Return the result, make result immutable (no better way on Python) | |
# Probably result is integer between 0 and 100, but still Bugs can happen. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment