1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 # An example that defines and uses stacks of integers.
16 # The implementation is done with a simple linked list.
17 # It features: free constructors, nullable types and some adaptive typing.
20 # A stack of integer implemented by a simple linked list.
21 # Note that this is only a toy class since a real linked list will gain to use
22 # generics and extends interfaces, like Collection, from the standard library.
24 # The head node of the list.
25 # Null means that the stack is empty.
26 private var head
: nullable ISNode = null
28 # Add a new integer in the stack.
31 self.head
= new ISNode(val
, self.head
)
34 # Remove and return the last pushed integer.
35 # Return null if the stack is empty.
39 if head
== null then return null
40 # Note: the followings are statically safe because of the
47 # Return the sum of all integers of the stack.
48 # Return 0 if the stack is empty.
54 # Note: the followings are statically safe because of
55 # the condition of the 'while'.
62 # Note: Because all attributes have a default value, a free constructor
63 # "init()" is implicitly defined.
66 # A node of a IntStack
68 # The integer value stored in the node.
71 # The next node, if any.
72 var next
: nullable ISNode
74 # Note: A free constructor "init(val: Int, next: nullable ISNode)" is
85 # Note: the 'for' control structure cannot be used on IntStack in its current state.
86 # It requires a more advanced topic.
87 # However, why not using the 'loop' control structure?
90 if i
== null then break
91 # The following is statically safe because of the previous 'if'.
95 # Note: 'or else' is used to give an alternative of a null expression.
97 print l
.pop
or else 0 # l.pop gives 5, so print 5
98 print l
.pop
or else 0 # l.pop gives null, so print the alternative: 0