Created
April 20, 2019 09:39
-
-
Save jrfondren/c2bc601f28a5c9349bdab52aa3270354 to your computer and use it in GitHub Desktop.
code samples sized for nim-lang.org's sample code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Sort input lines | |
import sequtils, strutils, algorithm | |
var lines = stdin.readAll.splitLines | |
lines.sort(cmp, Descending) | |
for line in lines: | |
echo line |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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