Implementation of linked list in Carbon #1799
pmqtt
started this conversation in
Language design
Replies: 2 comments 7 replies
-
Carbon's equivalent for null will likely be Bear in mind that Carbon is still being built, and this won't work yet. |
Beta Was this translation helpful? Give feedback.
4 replies
-
Hi folks, package ExplorerTest api;
class ListElement{
fn Create(value: i32)->ListElement{
return {
.element = Optional(i32).Create(value),
.next = Optional(ListElement*).CreateEmpty()
};
}
fn set[addr me: Self*] (value: Optional(ListElement*)){
(*me).next = value;
}
var element: Optional(i32);
var next: Optional(ListElement*);
}
class List{
fn Create() -> List{
return {.next = Optional(ListElement*).CreateEmpty() };
}
fn insert[addr me: Self*] (value: i32){
if( not (*me).next.has_value() ){
(*me).next = Optional(ListElement*).Create( heap.New(ListElement.Create(value)) );
return;
}
var iter: Optional(ListElement*) = (*me).next;
var node: auto = (iter.get());
while((*node).next){
iter = (*node).next;
node = (iter.get());
}
var v : ListElement* = iter.get();
var x: Optional(ListElement*) = Optional(ListElement*).Create( heap.New(ListElement.Create(value) ));
(*v).set(x);
}
fn print[me: Self] (){
var iter: Optional(ListElement*) = me.next;
while(iter){
var node: auto = *(iter.get());
Print("{0}",node.element.get());
var node_ptr: auto = iter.get();
iter = node.next;
}
}
fn clean[addr me: Self*] (){
var head: auto = (*me).next;
while(head){
var tmp: auto = head;
head = (*head.get()).next;
heap.Delete(tmp.get());
}
(*me).next= Optional(ListElement*).CreateEmpty();
}
var next: Optional(ListElement*);
}
fn Main() -> i32{
var list: List = List.Create();
list.insert(1);
list.insert(2);
list.insert(3);
list.insert(4);
list.print();
list.clean();
list.print();
list.insert(1);
list.insert(2);
list.insert(3);
list.insert(4);
list.print();
return 0;
} |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hello folks,
I try to implement a linked list in carbon... For the reason, to check how powerfull is the language in current state...
But I find many hurdles by the implementation!
First, Carbon has no null or nil value. Ok, I have try to solve it with using choice and declare my own NIL...
But here is the problem, that is impossible. Because NodeItem or Node should be forward declared.
I think we should thinking about such problems and how to solve it.
Best regrads!
Beta Was this translation helpful? Give feedback.
All reactions