cmc/learn

My personal learning area.

clone: git clone https://gitbay.org/cmc/learn.git

30d59f06f46ed48d9de1c375cd285f59f46a4747

verified · cmc

author: Christian Cleberg <hello@cleberg.net> · 2025-06-04T18:48:51Z

feat: add nim examples
 nim/colordiff/colordiff.nim | 47 +++++++++++++++++++++++++++++++++++++++++++++
 nim/colordiff/file1.txt     |  6 ++++++
 nim/colordiff/file2.txt     |  7 +++++++
 nim/hello_world.nim         |  5 +++++
 4 files changed, 65 insertions(+)

diff --git a/nim/colordiff/colordiff.nim b/nim/colordiff/colordiff.nim
new file mode 100644
index 0000000..69920d4
--- /dev/null
+++ b/nim/colordiff/colordiff.nim
@@ -0,0 +1,47 @@
+import os, strutils, terminal
+
+proc readLines(path: string): seq[string] =
+  result = @[]
+  for line in lines(path):
+    result.add(line)
+
+proc diffFiles(fileA, fileB: string) =
+  let
+    linesA = readLines(fileA)
+    linesB = readLines(fileB)
+
+  var
+    i = 0
+    j = 0
+
+  while i < linesA.len or j < linesB.len:
+    if i < linesA.len and j < linesB.len:
+      if linesA[i] == linesB[j]:
+        echo linesA[i]  # identical, no color
+        i.inc
+        j.inc
+      else:
+        setForegroundColor(fgRed)
+        echo "- ", linesA[i]
+        resetAttributes()
+        setForegroundColor(fgGreen)
+        echo "+ ", linesB[j]
+        resetAttributes()
+        i.inc
+        j.inc
+    elif i < linesA.len:
+      setForegroundColor(fgRed)
+      echo "- ", linesA[i]
+      resetAttributes()
+      i.inc
+    elif j < linesB.len:
+      setForegroundColor(fgGreen)
+      echo "+ ", linesB[j]
+      resetAttributes()
+      j.inc
+
+when isMainModule:
+  if paramCount() != 2:
+    echo "Usage: colordiff <file1> <file2>"
+    quit(1)
+  diffFiles(paramStr(1), paramStr(2))
\ No newline at end of file
diff --git a/nim/colordiff/file1.txt b/nim/colordiff/file1.txt
new file mode 100644
index 0000000..870afb3
--- /dev/null
+++ b/nim/colordiff/file1.txt
@@ -0,0 +1,6 @@
+Line one
+Line two
+Line three
+Line four
+Line six
+Line eight
\ No newline at end of file
diff --git a/nim/colordiff/file2.txt b/nim/colordiff/file2.txt
new file mode 100644
index 0000000..9afa048
--- /dev/null
+++ b/nim/colordiff/file2.txt
@@ -0,0 +1,7 @@
+Line one
+Line 2
+Line three
+Line five
+Line six
+Line seven
+Line eight
\ No newline at end of file
diff --git a/nim/hello_world.nim b/nim/hello_world.nim
new file mode 100644
index 0000000..01704ad
--- /dev/null
+++ b/nim/hello_world.nim
@@ -0,0 +1,5 @@
+# to build:
+# nim c -d:release hello_world.nim
+# ./hello_world.nim
+
+echo "Hello from Nim!"