Skip to content

Instantly share code, notes, and snippets.

# this works ##########################
type
Foo[N: static[int], T] = object
elements: array[0..(N - 1), T]
var f2 = Foo[2, float](elements: [1.0, 2.0])
var f3 = Foo[3, float](elements: [1.0, 2.0, 3.0])
@gmpreussner
gmpreussner / gist:34b6bf829f8a2e46b2bb
Created January 25, 2015 06:53
Generic tuple types
# compiles
type Foo = tuple[x, y: float]
proc foo(a, b: Foo): bool = (a.x == b.x) and (a.y == b.y)
var f = (1.0, 2.0)
check(foo(f, f))
# does not compile
type Bar[T] = tuple[x, y: T]
proc bar(a, b: Bar): bool = (a.x == b.x) and (a.y == b.y) # Error: undeclared identifier: 'x'
var b = (1.0, 2.0)
@gmpreussner
gmpreussner / gist:17d4c61216cb744e270e
Created February 14, 2015 16:29
Generic param in nested type resolve issue
# Suppose we have the following type for a rectangular array:
type
RectArray*[R, C: static[int], T] = distinct array[R * C, T]
var a23: RectArray[2, 3, int]
var a32: RectArray[3, 2, int]
echo "a23: ", a23.R, "x", a23.C
echo "a32: ", a32.R, "x", a32.C
@gmpreussner
gmpreussner / gist:af6cceaa2c54403b6c87
Created February 14, 2015 20:15
static[T] hangs compiler
type
RectArray*[R, C: static[int], T] = distinct array[R * C, T]
StaticMatrix*[R, C: static[int], T] = object
elements*: RectArray[R, C, T]
StaticVector*[N: static[int], T] = StaticMatrix[N, 1, T]
proc foo*[N, T](a: StaticVector[N, T]): T = 0.T
framework
packageA
bin
docs
src
module1.nim
module2.nim
module3.nim
tests
tmodule1.nim
@gmpreussner
gmpreussner / midlinterface.nim
Last active October 6, 2015 01:43
MIDL interface glue code generator
import macros
macro midlInterface*(head: expr; body: stmt): stmt {.immediate.} =
## Generates the glue code required for MIDL interface types.
##
## For example, the following declaration...
##
## midlInterface IUnknown:
## proc queryInterface*(riid: Iid; outObj: ptr pointer): HResult
@gmpreussner
gmpreussner / gist:42316c11c9c6d4479d21
Created October 18, 2015 06:42
Bug with generics/concepts
type
Foo[T] = concept x, y
foo(x, y) is bool
Bar[T] = object
b: T
when true: # the following works
proc foo(x, y: Bar): bool = true
import macros
const nmax = 500
type
Complex*[T] = object
re*: T
im*: T
converter toComplex*[T](x: tuple[re, im: T]): Complex[T] =
type IntArray[T; N: static[int]] = array[N, T]
proc ones[T](N: static[int]): IntArray[T, N] =
for i in 0 .. < N:
result[i] = 1
echo @[ones[int](5)]
type
Foo[T] = ref object
x: T
Bar[N: static[int], T] = ref object
a: array[N, T]
x: T
Foobar[N: static[int], T] = object
b: Bar[N, T]