aboutsummaryrefslogtreecommitdiff
path: root/prescheme-nim-local/nim/example.nim
diff options
context:
space:
mode:
Diffstat (limited to 'prescheme-nim-local/nim/example.nim')
-rw-r--r--prescheme-nim-local/nim/example.nim51
1 files changed, 51 insertions, 0 deletions
diff --git a/prescheme-nim-local/nim/example.nim b/prescheme-nim-local/nim/example.nim
new file mode 100644
index 0000000..6757120
--- /dev/null
+++ b/prescheme-nim-local/nim/example.nim
@@ -0,0 +1,51 @@
+# Example from nim front page. Compile with:
+#
+# nim -c -d:release c example && ./example
+
+import std/strformat
+
+type
+ Person = object
+ name: string
+ age: Natural # Ensures the age is positive
+
+let people = [
+ Person(name: "John", age: 45),
+ Person(name: "Kate", age: 30)
+]
+
+for person in people:
+ # Type-safe string interpolation,
+ # evaluated at compile time.
+ echo(fmt"{person.name} is {person.age} years old")
+
+
+# Thanks to Nim's 'iterator' and 'yield' constructs,
+# iterators are as easy to write as ordinary
+# functions. They are compiled to inline loops.
+iterator oddNumbers[Idx, T](a: array[Idx, T]): T =
+ for x in a:
+ if x mod 2 == 1:
+ yield x
+
+for odd in oddNumbers([3, 6, 9, 12, 15, 18]):
+ echo odd
+
+
+# Use Nim's macro system to transform a dense
+# data-centric description of x86 instructions
+# into lookup tables that are used by
+# assemblers and JITs.
+import macros, strutils
+
+macro toLookupTable(data: static[string]): untyped =
+ result = newTree(nnkBracket)
+ for w in data.split(';'):
+ result.add newLit(w)
+
+const
+ data = "mov;btc;cli;xor"
+ opcodes = toLookupTable(data)
+
+for o in opcodes:
+ echo o