ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Nim Compile-Time String to Integer Conversion

Nim

Goal -- WPM

Ready
Exercise Algorithm Area
1import macros
2import strutils
3
4macro stringToIntLiteral*(s: typedesc[string]): int =
5if s.kind != nnkStrLit:
6raise newNimNode(nnkCall, "raise", newLit("Argument must be a string literal."))
7
8let strVal = s.strVal
9try:
10let intVal = parseInt(strVal)
11result = newNimNode(nnkIntLit, $intVal)
12except ValueError:
13raise newNimNode(nnkCall, "raise", newLit("Invalid integer literal: '" & strVal & "'"))
14
15return result
16
17proc main() =
18let num1 = stringToIntLiteral("123")
19echo "Num1: ", num1, " (type: ", typeof(num1), ")"
20
21let num2 = stringToIntLiteral("-456")
22echo "Num2: ", num2, " (type: ", typeof(num2), ")"
23
24let num3 = stringToIntLiteral("0")
25echo "Num3: ", num3, " (type: ", typeof(num3), ")"
26
27# Example of invalid input (will cause compile-time error)
28# let invalidNum = stringToIntLiteral("abc")
29# echo "Invalid Num: ", invalidNum
30
31# Example of non-literal input (will cause compile-time error)
32# let runtimeStr = "789"
33# let runtimeNum = stringToIntLiteral(runtimeStr)
34# echo "Runtime Num: ", runtimeNum
35
36main()
Algorithm description viewbox

Nim Compile-Time String to Integer Conversion

Algorithm description:

This Nim code defines a compile-time macro `stringToIntLiteral` that converts a string literal into an integer. It leverages `strutils.parseInt` within the macro to perform the conversion during compilation, ensuring that the resulting value is a compile-time constant. This is useful for embedding configuration values or constants that are known at compile time.

Algorithm explanation:

The `stringToIntLiteral` macro takes a `typedesc[string]` argument, which signifies that it expects a string literal. Inside the macro, it first checks if the input `s` is indeed a string literal (`nnkStrLit`). If not, it raises a compile-time error. If it is a string literal, it extracts the string value (`s.strVal`) and attempts to parse it into an integer using `strutils.parseInt`. If `parseInt` succeeds, a new integer literal node (`nnkIntLit`) is created with the parsed value and returned. If `parseInt` fails (e.g., the string is not a valid integer), a compile-time error is raised. The time complexity of the macro execution is effectively O(L) where L is the length of the string literal, due to the `parseInt` operation. The space complexity is O(1) during macro expansion.

Pseudocode:

Macro stringToIntLiteral(s):
  If s is not a string literal:
    Raise compile-time error "Argument must be a string literal."
  Get the string value from s
  Try:
    Parse the string value into an integer (intVal)
    Create and return a new integer literal node with intVal
  Catch ValueError:
    Raise compile-time error "Invalid integer literal: '" + string value + "'"