Skip to content

Instantly share code, notes, and snippets.

@jrfondren
Created April 20, 2019 09:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jrfondren/c2bc601f28a5c9349bdab52aa3270354 to your computer and use it in GitHub Desktop.
Save jrfondren/c2bc601f28a5c9349bdab52aa3270354 to your computer and use it in GitHub Desktop.
code samples sized for nim-lang.org's sample code
# DNS query
import nativesockets
iterator items(ai: ptr AddrInfo): string =
var current = ai
while current != nil:
yield current.aiAddr.getAddrString
current = current.aiNext
let ips = getAddrInfo("www.nim-lang.org",
Port 80, AfUnspec)
defer: freeAddrInfo ips
for ip in ips: echo ip
type FB = enum
Raw, Fizz, Buzz, FizzBuzz
func classify(n: int): FB =
let
by3 = n mod 3 == 0
by5 = n mod 5 == 0
FB((by3.int shl 1) or by5.int)
for n in 1 .. 100:
case classify(n)
of Raw: echo n
of Fizz: echo "Fizz"
of Buzz: echo "Buzz"
of FizzBuzz: echo "FizzBuzz"
# Sort input lines
import sequtils, strutils, algorithm
var lines = stdin.readAll.splitLines
lines.sort(cmp, Descending)
for line in lines:
echo line
# Unhygenic macros
template given(val, stmts: untyped) =
block:
let it {.inject.} = val
stmts
given "long or side-effecting".len:
echo it
echo it / 6
echo it * 2
doAssert it == 22
# see re.`=~` for more
# Who did the most damage?
import re, tables, strutils
var foes = initCountTable[string]()
for line in "combat.log".lines:
if line =~ re"^(\w+) hit for (\d+)":
let damage = matches[1].parseInt
foes.inc(matches[0], damage)
foes.sort
for foe, damage in foes:
echo(damage, " ", foe)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment