Code examples

Be aware that the code is generated by GPT-4 and may contain inaccuracies...

A few Nim source code examples

Note that the GTP4-generated import statements are not really needed but show how you can import used modules.

Snippet 1: Hello World
Description: This simple program prints “Hello, World!” to the console.

# Import the necessary modules
import std/[strutils, os]

# This is the main procedure
proc main() =
  # Print "Hello, World!" to the console
  echo "Hello, World!"

# Call the main procedure
main()

Snippet 2: Fibonacci Sequence
Description: This program prints the first 10 numbers of the Fibonacci sequence.

# Import the necessary modules
import std/[strutils, os]

# Function to calculate the nth number in the Fibonacci sequence
proc fibonacci(n: int): int =
  if n <= 1:
    return n
  else:
    return fibonacci(n - 1) + fibonacci(n - 2)

# Main procedure
proc main() =
  for i in 0..9:
    echo "Fibonacci(", i, ") = ", fibonacci(i)

# Call the main procedure
main()

Snippet 3: Basic Input/Output
Description: This program takes a user’s name as input and greets them.

# Import the necessary modules
import std/[strutils, os]

# Main procedure
proc main() =
  # Ask the user for their name
  echo "Please enter your name: "
  var name: string = readLine(stdin)
  
  # Greet the user
  echo "Hello, ", name, "!"

# Call the main procedure
main()

Snippet 4: Factorial Calculation
Description: This program calculates the factorial of a given number using iteration.

# Import the necessary modules
import std/[strutils, os]

# Function to calculate the factorial of a number
proc factorial(n: int): int =
  var result = 1
  for i in 1..n:
    result *= i
  return result

# Main procedure
proc main() =
  let num = 5
  echo "Factorial of ", num, " is ", factorial(num)

# Call the main procedure
main()

These are just a few examples of how Nim code typically looks. You can compile and run these code snippets to understand the structure and style of Nim programming.

For more examples, see