Sfoglia il codice sorgente

huzzah, pointers in the list itself seem to be the solution.

because that's actually what we want here: we want to *reference* other
immutable lists in our own, so that we don't have to create them twice.

in the previous attempts, any "list construction" using other lists
would move that list, which isn't what we want.

we also need references both in the data structure *and* the functions
using them, to be able to apply those functions and still be able to use
the arguments we used afterwards.

also, the lifetime annotations are quite tricky.

now, should we *still* use boxes inside the references? if references
are really allocated on the stack, then we probably should. but i think
if we let users box the list heads themselves, it's better, because we
don't want to dictate where to allocate things.
Lucas Stadler 11 anni fa
parent
commit
958ea7e37f
1 ha cambiato i file con 24 aggiunte e 0 eliminazioni
  1. 24 0
      rust/pointers.rs

+ 24 - 0
rust/pointers.rs

@ -114,9 +114,33 @@ mod list_with_ref {
114 114
    }
115 115
}
116 116
117
mod list_with_ref_box {
118
    #[deriving(Show)]
119
    enum List<'a, A: 'a> {
120
        Nil,
121
        Cons(A, &'a Box<List<'a A>>)
122
    }
123
124
    pub fn cons<'a, A>(x: A, xs: &'a Box<List<'a A>>) -> List<'a A> {
125
        Cons(x, xs)
126
    }
127
128
    pub fn run() {
129
        println!("\nlist_with_ref_box:");
130
131
        let nil = &box Nil;
132
        let l: &Box<List<int>> = &box cons(1, nil);
133
134
        println!("l = {:?}", l);
135
        println!("cons(2, l) = {:?}", cons(2, l));
136
        println!("cons(3, l) = {:?}", cons(3, l));
137
    }
138
}
139
117 140
pub fn main() {
118 141
    wrapped::run();
119 142
120 143
    list_with_box::run();
121 144
    list_with_ref::run();
145
    list_with_ref_box::run();
122 146
}