Skip to content

Instantly share code, notes, and snippets.

@leveled
leveled / clipboard_to_image.sh
Created February 3, 2021 14:52
Selection from clipboard to image on linux
xclip –selection clipboard –t image/png (or jpg if it is available) –o > /tmp/nameofyourfile.png
@leveled
leveled / modules.nim
Created February 3, 2021 13:35
Modules in nim
# Module A
var
x*, y: int
proc `*` *(a, b: seq[int]): seq[int] =
# allocate a new sequence:
newSeq(result, len(a))
# multiply two int sequences:
for i in 0..len(a)-1: result[i] = a[i] * b[i]
@leveled
leveled / advanced_types.nim
Created February 3, 2021 13:34
Complex variable types in nim
#Type with enum
type
Direction = enum
north, east, south, west
var x = south # `x` is of type `Direction`; its value is `south`
echo x # writes "south" to `stdout`
#Subrange
type
@leveled
leveled / print_complex_vars.nim
Created February 3, 2021 13:30
Print complex variables nim
var
myBool = true
myCharacter = 'n'
myString = "nim"
myInteger = 42
myFloat = 3.14
echo myBool, ":", repr(myBool)
# --> true:true
echo myCharacter, ":", repr(myCharacter)
# --> n:'n'
@leveled
leveled / type_conversion.nim
Created February 3, 2021 13:29
Type conversion in Nim
var
x: int32 = 1.int32 # same as calling int32(1)
y: int8 = int8('a') # 'a' == 97'i8
z: float = 2.5 # int(2.5) rounds down to 2
sum: int = int(x) + int(y) + int(z) # sum == 100
@leveled
leveled / iterators.nim
Created February 3, 2021 13:29
Iterators in Nim.nim
iterator countup(a, b: int): int =
var res = a
while res <= b:
yield res
inc(res)
@leveled
leveled / procedures.nim
Created February 3, 2021 13:28
Procedures in Nim
#Procedure with implicit return result
proc sumTillNegative(x: varargs[int]): int =
for i in x:
if i < 0:
return
result = result + i
echo sumTillNegative() # echos 0
echo sumTillNegative(3, 4, 5) # echos 12
echo sumTillNegative(3, 4 , -1 , 6) # echos 7
@leveled
leveled / control_flow_statements.nim
Created February 3, 2021 13:26
Control flow statements in Nim
#Basic if statement
let name = readLine(stdin)
if name == "":
echo "Poor soul, you lost your name?"
elif name == "name":
echo "Very funny, your name is name."
else:
echo "Hi, ", name, "!"
#Basic case statement
@leveled
leveled / declaring_variables.nim
Last active February 3, 2021 13:20
Declaring variables in nim
var x, y: int # declares x and y to have the type ``int``
var
x, y: int
# a comment can occur here too
a, b, c: string
#Constants
const x = "abc" # the constant x contains the string "abc"
@leveled
leveled / nim_lexical_elements.nim
Created February 3, 2021 13:19
Nim lexical elements
r"C:\program files\nim"
# A comment.
var myVariable: int ## a documentation comment
#[
You can have any Nim code text commented
out inside this with no indentation restrictions.
yes("May I ask a pointless question?")