Guest User

Untitled

a guest
Mar 8th, 2018
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Nim 1.46 KB | None | 0 0
  1. type
  2.   List{.unchecked.}[T] = array[0..0, T]
  3.   Stack[T] = object
  4.     size: Natural
  5.     head: int
  6.     data: ptr List[T]
  7.  
  8.  
  9. proc new_stack[T](size: Natural = 2): Stack[T] =
  10.   var data = cast[ptr List[T]](alloc(size * sizeof(T)))
  11.   return Stack[T](size: size, head: -1, data: data)
  12.  
  13.  
  14. proc destroy_stack(stack: Stack) =
  15.   if stack.data != nil:
  16.     dealloc stack.data
  17.     echo "destroy stack."
  18.  
  19.  
  20. proc `[]`[T](stack: Stack[T], i: Natural): T =
  21.   if i >= stack.size:
  22.     raise newException(IndexError, "request for index out of bounds.")
  23.   return stack.data[][int(i)]
  24.  
  25.  
  26. proc `[]=`[T](stack: Stack[T], i: Natural, item: T) =
  27.   if i >= stack.size:
  28.     raise newException(IndexError, "request to set out of bounds index.")
  29.   stack.data[][int(i)] = item
  30.  
  31.  
  32. proc peek[T](stack: Stack[T]): T =
  33.   if stack.head < 0:
  34.     raise newException(IndexError, "inspect on empty stack.")
  35.   result = stack.data[stack.head]
  36.  
  37.  
  38. proc push[T](stack: Stack[T], item: T) =
  39.   if stack.head == stack.size - 1:
  40.     var data_expanded = cast[ptr List[T]](alloc(stack.size * 2 * sizeof(T)))
  41.     copyMem(data_expanded, stack.data, stack.size)
  42.     dealloc(stack.data)
  43.     stack.data = data_expanded
  44.     echo("expand stack.")
  45.  
  46.   stack.head += 1
  47.   stack[stack.head] = item
  48.  
  49.  
  50.  
  51. block:
  52.   var stack = new_stack[int]()
  53.   echo(stack.size)
  54.   for i in 0..<stack.size:
  55.     echo(stack[i])
  56.     stack.push(i + 2)
  57.   for i in 0..<stack.size:
  58.     echo(stack.peek())
  59.   destroy_stack(stack)
Add Comment
Please, Sign In to add comment