# Competitive programming in Nim

In the afternoon, I came cross the Nim programming language again on Lobsters. I first learned some basics of the language in 2015, but had not touched it since then.

"Nim is a statically typed compiled systems programming language. It combines successful concepts from mature languages like Python, Ada and Modula.", according to its website.

Basic features: parametric polymorphism. Advanced features: macros (including term-rewriting macros), compile-time function execution, effect system, concepts

An idea popped into my mind: why not solve some coding challenges in Nim?

As a niche language, it is not supported on many coding challenge websites. Fortunately, the Nim compiler generates C code. With a small amount of work, we can build a self-contained C source file suitable for submission.

Let's take a LeetCode challenge as an example. We write the main algorithm in Nim and use the emit pragma to write a C wrapper.

Then, create a self-contained C file with the approach described on https://zen.su/posts/amalgamating-nim-programs/.

Prepare nim.cfg and run nim c -d:danger --gc:arc -d:useMalloc a.nim to generate a_comb.c:

-d:useMalloc avoids Nim's own memory manager and can greatly decrease the C code size. There are several choices for --gc, but --gc:arc can genreated the smallest C code. Unfortunately --gc:none does not work.

The CIL generated file looks like:

The LeetCode environment includes some glibc headers like <stdio> which result in some conflicts due to duplicate definitions of struct _IO_FILE and some GNU extern inline functions. Let's write a Nim program to remove the duplicate definitions.

Finally, run { echo '/*'; cat a.nim; echo '*/'; cat for-submit.c; } | xclip -i -selection clipboard and paste the content into the LeetCode editor:) Well, the Nim source is not really needed but it is useful for archive purposes.

for-submitted.c is suitable for 64-bit Linux environment.

TODO Figure out how to support Codeforces (Windows with a 64KiB source code size limit).

If CIL fails to handle some syntax, use another deduplicator: