From b2b9a8324f1c65d15fa5dac7d8d4e9dd734f8c65 Mon Sep 17 00:00:00 2001 From: kitsunyan Date: Sat, 21 Apr 2018 10:09:43 +0300 Subject: Introduce "List[T]" type --- src/lists.nim | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/package.nim | 3 +-- 2 files changed, 59 insertions(+), 2 deletions(-) create mode 100644 src/lists.nim diff --git a/src/lists.nim b/src/lists.nim new file mode 100644 index 0000000..cf1b0c5 --- /dev/null +++ b/src/lists.nim @@ -0,0 +1,58 @@ +import sequtils + +type + List*[T] = ref object of RootObj + next: List[T] + data: T + +iterator items*[T](list: List[T]): T = + var l = list + while l != nil: + yield l.data + l = l.next + +proc list*[T](items: varargs[T]): List[T] = + var last: List[T] = nil + for i in countdown(items.high, items.low): + new(result) + result.data = items[i] + result.next = last + last = result + +proc reversed*[T](list: List[T]): List[T] = + var last: List[T] = nil + for item in list: + new(result) + result.data = item + result.next = last + last = result + +proc `^&`*[T](data: T, list: List[T]): List[T] = + new(result) + result.next = list + result.data = data + +proc `^&`*[T](data: openarray[T], list: List[T]): List[T] = + result = list + for i in countdown(data.high, data.low): + result = data[i] ^& result + +static: + # lists test + template testList[T](list: List[T], testSeq: openArray[T]) = + block: + let s = toSeq(list.items) + if s != @testSeq: raise newException(SystemError, "list: " & $s) + + let l1 = list[int]() + testList(l1, []) + let l2 = 1 ^& l1 + testList(l2, [1]) + let l3 = list(1, 2, 3) + testList(l3, [1, 2, 3]) + let l4 = l3.reversed + testList(l4, [3, 2, 1]) + let l5 = 4 ^& l4 + testList(l5, [4, 3, 2, 1]) + let l6 = 8 ^& [7, 6] ^& 5 ^& l5 + testList(l6, [8, 7, 6, 5, 4, 3, 2, 1]) diff --git a/src/package.nim b/src/package.nim index 70fe2eb..f0a4ee1 100644 --- a/src/package.nim +++ b/src/package.nim @@ -1,6 +1,5 @@ import - future, options, os, re, sequtils, sets, strutils, tables, - utils, + future, options, os, re, sequtils, sets, strutils, tables, utils, "wrapper/alpm" type -- cgit v1.2.3-70-g09d2