Dhghomon / rust-fsharp

Rust - F# - Rust reference
MIT License
239 stars 14 forks source link

F#'s linked list are not like you say in Rust #21

Open ChayimFriedman2 opened 3 years ago

ChayimFriedman2 commented 3 years ago

More like:

#[derive(Debug)]
enum FSharpList<T> {
    Cons(T, Box<FSharpList<T>>),
    Nil,
}

impl<T> FSharpList<T> {
    fn new<I: IntoIterator<Item = T>>(input: I) -> Self {
        let mut iter = input.into_iter();
        match iter.next() {
            Some(item) => Self::Cons(item, Box::new(Self::new(iter))),
            None => Self::Nil,
        }
    }
}

fn main() {
    let fsharp_list = FSharpList::new(0..=10);
    println!("{:#?}", fsharp_list);
}

Printing:

Cons(
    0,
    Cons(
        1,
        Cons(
            2,
            Cons(
                3,
                Cons(
                    4,
                    Cons(
                        5,
                        Cons(
                            6,
                            Cons(
                                7,
                                Cons(
                                    8,
                                    Cons(
                                        9,
                                        Cons(
                                            10,
                                            Nil,
                                        ),
                                    ),
                                ),
                            ),
                        ),
                    ),
                ),
            ),
        ),
    ),
)

({:#?} pretty-print Debug representation, in case you didn't know.)

Dhghomon commented 3 years ago

This looks more like just the Cons list from the Book, no? An F# list is always of type head and tail (int, list or however it's written) and allows for easy access to the head value.

Not that my imagined implementation is anything outstanding (and I was hoping for someone to come along and improve it) but I don't see anything for easy access to the head of the list.

ChayimFriedman2 commented 3 years ago

but I don't see anything for easy access to the head of the list.

In yours or mine?