Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ####################################### Definition
- type Container* = ref object
- list: seq[int]
- proc newContainer(): Container = # Explicit new
- new(result)
- result.list = @[]
- proc newContainer(a: var Container) = # Safe new
- if a == nil: a = newContainer()
- proc length*(a: Container): int = # Safe length
- return if a == nil: 0 else: a.list.len
- proc isEmpty*(a: Container): bool = # Safe isEmpty
- return a.length == 0
- proc add*(a: var Container, x: int) = # Safe add
- a.newContainer
- a.list.add x
- iterator items*(a: Container): int = # Safe iterator
- if not a.isEmpty:
- for i in a.list: yield i
- ####################################### Example
- var a: Container # Nil, which represents a safe empty container, no need to check for nil
- echo "is empty? ", a.isEmpty #> true
- for i in a: echo i # Nothing is echoed, no error
- echo "Length is:", a.length #> 0
- a.add 5 # Nil until 5 was added
- a.add 6 # Container at this point
- echo "Length is:", a.length #> 2
- for i in a: echo i #> 5
- #> 6
Advertisement
Add Comment
Please, Sign In to add comment