Tips for golfing in Nim

11

What general tips do you have for golfing in Nim? I'm looking for ideas which can be applied to code-golf problems and which are also at least somewhat specific to Nim (e.g. "remove comments" is not an answer).

Please post one tip per answer.

trichoplax

Posted 2016-11-26T11:29:00.927

Reputation: 10 499

Answers

7

Use the future module

The future module contains two main byte-saving features: lambdas and list comprehensions. Lambdas are extremely useful.

For example, this:

proc f(s:any):any=s&", world!"

can be shortened to this:

import future
s=>s&", world!"

which saves a byte. Note, however, that lambdas can't be used outside of a parameter list -- so to test your code, you'll have to do something like this:

import future
proc test(f: string -> string) = echo f "Hello"
test(s=>s&", world!")

As well, list comprehensions can be used with the future module. For example, this code prints a seq (@[...]) of all squares less than 100 divisible by 4:

import future
echo lc[x*x|(x<-1..9,x*x mod 4==0),int]

Copper

Posted 2016-11-26T11:29:00.927

Reputation: 3 684

For a fairer comparison it should be noted that you can sometimes use any instead of string (I'm assuming you chose the longest type name), but this still saves regardless. – Sp3000 – 2016-11-26T23:43:13.430

@Sp3000 I didn't know you could use any, thanks for the tip! You should post that as an answer. – Copper – 2016-11-27T11:55:42.667

For an even better comparison, you can do proc(s:any):any=s&", world!", dropping the <space>f for an anonymous proc – Sp3000 – 2016-12-20T09:57:10.190

7

Flexible call syntax

Nim is pretty flexible when it comes to function call syntax. For example, here are some ways to call a function with one argument:

ord(c)
ord c
c.ord

And ways to call a function with two arguments:

max(a,b)
a.max(b)
a.max b

Choose the golfiest version that works right for your situation, especially regarding precedence. For example, compare:

abs(n)+2
n.abs+2
(abs n)+2

As opposed to:

abs(n+2)
(n+2).abs
abs n+2

Sp3000

Posted 2016-11-26T11:29:00.927

Reputation: 58 729

Note that max a,b even works (sometimes). – Copper – 2016-11-26T18:49:46.350

6

Unsigned operators

When working with nonnegative integers, sometimes it's better to use unsigned operators. Specifically, if possible, use /% and %% instead of div and mod.

Sp3000

Posted 2016-11-26T11:29:00.927

Reputation: 58 729