Guest User

Container.nim

a guest
Apr 23rd, 2015
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Nim 1.25 KB | None | 0 0
  1. ####################################### Definition
  2. type Container* = ref object
  3.   list: seq[int]
  4.  
  5. proc newContainer(): Container =        # Explicit new
  6.   new(result)
  7.   result.list = @[]
  8.  
  9. proc newContainer(a: var Container) =   # Safe new
  10.   if a == nil: a = newContainer()
  11.  
  12. proc length*(a: Container): int =       # Safe length
  13.   return if a == nil: 0 else: a.list.len
  14.  
  15. proc isEmpty*(a: Container): bool =     # Safe isEmpty
  16.   return a.length == 0
  17.  
  18. proc add*(a: var Container, x: int) =   # Safe add
  19.   a.newContainer
  20.   a.list.add x
  21.  
  22. iterator items*(a: Container): int =    # Safe iterator
  23.   if not a.isEmpty:
  24.     for i in a.list: yield i
  25.    
  26. ####################################### Example
  27. var a: Container                        # Nil, which represents a safe empty container, no need to check for nil
  28.  
  29. echo "is empty? ", a.isEmpty            #> true
  30. for i in a: echo i                      # Nothing is echoed, no error
  31.  
  32. echo "Length is:", a.length             #> 0
  33. a.add 5                                 # Nil until 5 was added
  34. a.add 6                                 # Container at this point
  35. echo "Length is:", a.length             #> 2
  36.  
  37. for i in a: echo i                      #> 5
  38.                                         #> 6
Advertisement
Add Comment
Please, Sign In to add comment