kllrnohj 6 days ago

You don't & generally shouldn't be in the first place, in any language. Linked lists are a very niche data structure, so generic code should ~never be using them. So it's a moot question. It's kinda like the complaints about how hard a doubly linked list is in Rust - it's just not important because it's not something you should be using 99.999% of the time anyway.

2
grayhatter 6 days ago

A linked list is just a simpler version of both a graph and a tree. What data structure would you suggest to represent both/either of those?

Or are you asserting, because you've never used them they're not common? Because while maybe I agree, and I don't often reach for a linked list, I've built plenty of trees and graphs.

kllrnohj 6 days ago

Trees and graphs serve useful roles, of course, but calling a linked list just a simpler version is a stretch. It'd be like calling an array a simplified B-tree. The simplification changes not just the implementation but also radically changes the applicability of the result.

grayhatter 6 days ago

except a tree or graph with multiple pointers is similar to linked list with one pointer.

where as a b-tree stored in an array without pointers probably shouldn't be called a b-tree.

or am I missing something?

roetlich 6 days ago

Well I personally almost never use linked lists, don't like them. But Zig seems to think otherwise, they have two implementations in the standard library.

I don't know much Zig, I just wanted to ask how to use the type that the article talks about?

Let's use the very simple example from the article. Let's say I want to extract this code into a function:

    while (node) |n| {
      const user: *User = @fieldParentPtr("node", n);
      std.debug.print("{any}\n", .{user});
      node = n.next;
    }
1. How does that look, what's the type signature of this function? 2. What happens if I put in a list doesn't contain users? Do I get a simple to understand compile time error, or can I segfault because I'm accessing bad memory?

And I don't think that would need any generics, since the list type isn't generic, right?

boomlinde 6 days ago

1. If you mean @fieldParentPtr, the first argument is a compile time-known name of a field, the second argument is a pointer to a field of that name in the parent type, which is inferred from the left hand side of the assignment

2. Then you're screwed. In Zig, using @fieldParentPtr on a field that doesn't have the given parent is unchecked illegal behavior, meaning that there are no checks that can catch it at compile time. This change basically guarantees that there will be a pretty serious foot gun every time you iterate over the items of a standard library list.

throwawaymaths 5 days ago

Is 2 really an issue? Just how often are you going to have multiple Node types going on in your codebase?

roetlich 6 days ago

Thank you, that answers all my questions.