惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
WordPress大学
WordPress大学
宝玉的分享
宝玉的分享
人人都是产品经理
人人都是产品经理
博客园 - 聂微东
IT之家
IT之家
V
V2EX
Jina AI
Jina AI
V
Visual Studio Blog
有赞技术团队
有赞技术团队
博客园 - 司徒正美
博客园 - 叶小钗
The Cloudflare Blog
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
小众软件
小众软件
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
博客园 - 三生石上(FineUI控件)
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Google DeepMind News
Google DeepMind News
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
腾讯CDC
Google Online Security Blog
Google Online Security Blog
博客园 - 【当耐特】
Apple Machine Learning Research
Apple Machine Learning Research
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
N
News and Events Feed by Topic
N
News and Events Feed by Topic
The Last Watchdog
The Last Watchdog
W
WeLiveSecurity
月光博客
月光博客
Security Archives - TechRepublic
Security Archives - TechRepublic
Webroot Blog
Webroot Blog
SecWiki News
SecWiki News
博客园_首页
罗磊的独立博客
量子位
Latest news
Latest news
I
Intezer
V
Vulnerabilities – Threatpost
A
Arctic Wolf
Last Week in AI
Last Week in AI
Recent Commits to openclaw:main
Recent Commits to openclaw:main
S
SegmentFault 最新的问题
S
Security Affairs
阮一峰的网络日志
阮一峰的网络日志
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
酷 壳 – CoolShell
酷 壳 – CoolShell
P
Palo Alto Networks Blog
C
CXSECURITY Database RSS Feed - CXSecurity.com
N
News | PayPal Newsroom

Lobsters

CIFSwitch: a non-universal Linux local root vulnerability RIPE NCC session fixation: poaching logins with an Atlas probe GNOME 2.20 but its Web Components Agentic Search for Context Engineering – Leonie Monigatti Garnix is shutting down [not OC] akashina.tngl.sh/jjc Concerning Emacs (and Jazz) Nitpicking the shell history scene in ‘Tron: Legacy’ What's cooking on SourceHut? Q2 2026 The tenth OpenPGP email summit Package managers that package package managers Clojure on Fennel part three: parsing WordPress at 23 Finding Miscompiles for Fun, Not Profit GitHub - creusot-rs/creusot: Creusot helps you prove your Rust code is correct. Announcing Rust 1.96.0 | Rust Blog A Love Letter to Neovim sqlite AGENTS.md Am I a Bad Friend? CSS vs. JavaScript • Josh W. Comeau Erlang Ecosystem Foundation - Supporting the BEAM community A brief note about slot access cost in Common Lisp Keyboard latency probe Rethinking the GNOME clipboard issues Back to the Building Blocks’ Building Blocks Tech Notes: Theseus: translating win32 to wasm Fast is better than slow Content-addressed Rust builds (or, what kache actually caches) Intent to Prototype: Embedding API Canada’s Bill C-22 and the security cost of collecting more data 5 PostgreSQL locking behaviors that trip people up okmij.org Stop advertising in your commits! | AksDev GitHub - mplsllc/macsurf: A modern web browser for Classic Mac OS 9 PowerPC. Real CSS3, ES5 JavaScript, native HTTPS — built with CodeWarrior on the Carbon API. Introducing DoomBench - Can Your Data Stack Run DOOM? What are some of your favourite developer tools? Building a Scalable Ingestion Pipeline with Temporal (Part 1) Converting shallow Git bundles into normal repositories Are you a member of any professional associations? What is a harmonic? An interactive comic about additive synthesis How Virtual Tables Work in the Itanium C++ ABI Using SwiftUI to Build a Mac-assed App in 2026 Rust (and Slint) on a jailbroken Kindle. ~jack/lambda-on-lambda - Serverless Haskell on AWS - sourcehut git Human proof for FOSS contributions Extremely simple internet radio controlled via IRC Announcing BABLR Splitting Konsole views from Helix to run tools | AksDev GitHub - yugr/rust-slides Serving files over HTTP three ways: synchronous, epoll, and io_uring update docs with information about building with build.py (#979) · astral-sh/python-build-standalone@c9c40c5 A Simple Makefile Tutorial On C extensions, portability, and alternative compilers Switching to Colemak | Pedro Alves Just How Bad Was The Intel IAPX432? Nix's Substituter List Is Not a Routing Table Accelerating copy_if using SIMD Lambda on Lambda: Serverless Haskell on AWS | Blog Announcing feed-repeat v1.0 Scaling Akvorado BMP RIB with sharding EYG news: A host of CLI improvements, new guides and new effects The social contract of writing JS Crossword C array types are weird; and related topics Flatpak will depend on systemd – OSnews Migrating from Go to Rust | corrode Rust Consulting A portentous reunion Vivado Licensing Options How my minimal, memory-safe Go rsync steers clear of vulnerabilities the entropy layer of a wavelet codec, on its own GitHub - nferhat/fht-compositor: A dynamic tiling Wayland compositor. Debian SE Linux and PinTheft Does bulk memmove speed up std::remove_if? (No.) 声明式部分更新 | Blog | Chrome for Developers Fully in-browser container builds Dianne Skoll's Web Site - Remind The Architecture of Open Source Applications (Volume 1)Berkeley DB Pardon MIE? - ironPeak Blog “Long-Term Support” doesn’t mean what you think Jira IS Turing-Complete May I recommend thinking of Emacs as your Fortress of Solitude hershey Floodgap Gopher-HTTP gateway gopher://thelambdalab.xyz/1cuneiforth/ HP QuickWeb, Singular And Pointless That one time I used Go panics for flow control A new suite of modern tools coming for editing and publishing RFCs From the Tabletop… The Digital Antiquarian Building a Host-Tuned GCC to Make GCC Compile Faster Are we self-sovereign PKI yet? Claw Patrol: an open-source security firewall for agents | Deno Revised^7 Report on Scheme, Large: Procedural Fascicle Draft is now public A Network Allow-List Won't Stop Exfiltration — André Graf From AFSK to Goertzel – µArt.cz Software For My New Home Server Introducing Neptune: Direct3D virtualization for QEMU AI Agent Bankrupted Their Operator While Trying to Scan DN42 - Lan Tian @ Blog mimalloc: A new, high-performance, scalable memory allocator for the modern era Making wl_shm fast The Soul of Maintaining a New Machine - Third Draft | Books in Progress What is Git made of?
Revealing the frontier with stacks and queues
dystroy.org · 2026-06-03 · via Lobsters

Being able to think in stacks and queues is a neglected super-power.

It's often a better way to see problems than recursion when trees and other graphs are involved.

CS Courses like to teach recursion, because it looks simple and elegant, especially when Functional Programming is in the curriculum, and especially when drawn on a black board.

You've probably already read a few times, and maybe experienced yourself, that recursion isn't always efficient, especially on modern computers.

But a more interesting point is that it's also often a poor mental model which makes programming more complex and less adaptable.

An even more interesting point is that sometimes recursion shines, and that's why it didn't go away.

But even that isn't the real point of this article.

Tree traversal

Let's start our exploration with the case of file tree traversal.

In the real world, you never list all deep files in a directory: you have to deal with user interruptions, timeouts, various limits. We'll keep it simple and simulate this complexity with just a maximum number of items.

Depth-first traversal in natural order

In Rust the recursive code could look like this:

fn add_first_paths_recursive(
    dir: &Path,
    list: &mut Vec<PathBuf>,
    max: usize,
) -> Result<(), io::Error> {
    if list.len() >= max { return Ok(()); }
    list.push(dir.to_path_buf());
    if dir.is_dir() {
        for entry in fs::read_dir(dir)? {
            let path = entry?.path();
            add_first_paths_recursive(&path, list, max)?;
            if list.len() >= max { break; }
        }
    }
    Ok(())
}

What this does, is it lists files as they would appear with a standard tree representation, Depth-First Search, and files listed in the same order as returned by the system.

The code is obvious, you know there won't be any surprise, the order will be as expected. There's of course the hidden cost of the stack allocation but it's minor.

Early exit behaviour is a little more painful, both in code (hard not to repeat it) and in execution (as the call stack is unwound, every step has to do the same test).

Now, let's have a look at a stack based function doing the same traversal in the same order. It's less pretty than expected:

fn add_first_paths_with_stack_dfs(
    dir: &Path,
    list: &mut Vec<PathBuf>,
    max: usize,
) -> Result<(), io::Error> {
    let mut todo = vec![dir.to_path_buf()];
    while let Some(current) = todo.pop() {
        if list.len() >= max { break; }
        if current.is_dir() {
            let mut children = Vec::new();
            for entry in fs::read_dir(&current)? {
                let path = entry?.path();
                children.push(path);
            }
            list.push(current);
            for path in children.into_iter().rev() {
                todo.push(path);
            }
        } else {
            list.push(current);
        }
    }
    Ok(())
}

As we add paths to a TODO list that we unstack, we need to iterate in reverse (hence the children.into_iter().rev()).

This makes the code much harder to decipher (and even to write right at first try).

Early exit is much better handled but let's be honest, this code is much less obvious.

Here recursion shines.

It may be a little less efficient when handling the constraints of real world applications, like interrupts, but in this case, the recursive code perfectly aligns with our intent.

When no order is required

If we're not trying to print a tree on the fly, recursion isn't the simplest solution.

This one is very simple with a stack acting as a TODO list of directories to visit:

fn add_first_paths_with_stack(
    dir: &Path,
    list: &mut Vec<PathBuf>,
    max: usize,
) -> Result<(), io::Error> {
    let mut todo = vec![dir.to_path_buf()];
    while let Some(current) = todo.pop() {
        if list.len() >= max { break; }
        if current.is_dir() {
            for entry in fs::read_dir(&current)? {
                let path = entry?.path();
                todo.push(path);
            }
        }
        list.push(current);
    }
    Ok(())
}

Nothing awkward in this one.

And because we reified the frontier, it's very easy to change the control flow, to deal with interrupts, pause the iteration, have interleaving tasks, like iterating on another tree at the same time, etc.

What if you want to fully explore the current level before moving deeper ?

This is a trivial change: just replace the LIFO stack with a FIFO queue (using a VecDeque in Rust):

fn add_first_paths_with_queue(
    dir: &Path,
    list: &mut Vec<PathBuf>,
    max: usize,
) -> Result<(), io::Error> {
    let mut todo = VecDeque::from([dir.to_path_buf()]);
    while let Some(current) = todo.pop_front() {
        if list.len() >= max { break; }
        if current.is_dir() {
            for entry in fs::read_dir(&current)? {
                let path = entry?.path();
                todo.push_back(path);
            }
        }
        list.push(current);
    }
    Ok(())
}

The control flow is still easy to handle and the logic can be tuned.

For example broot builds upon this to provide efficient search and parallel descent without locking the UI.

Graph exploration

When the graph is more connected than a tree, exploring it with pure recursion becomes impossible.

But the stack/queue approach stays simple.

For example, here's returning all the nodes that can be reached from one:

fn reachable_from(root: Node) -> HashSet<Node> {
    let mut visited = HashSet::new();
    let mut todo = VecDeque::new();
    visited.insert(root);
    todo.push_back(root);
    while let Some(current) = todo.pop_front() {
        for neighbour in neighbours_of(current) {
            if visited.insert(neighbour) { // Returns false if already present
                todo.push_back(neighbour);
            }
        }
    }
    visited
}

The execution frontier isn't stored in a call stack but in the two variables visited and todo. You could wrap them in a struct and implement Iterator, so that callers may deal with early breaks as they wish.

This is also easy to tune:

  • Use a Vec for todo instead of the VecDeque and you explore far nodes first (equivalent of DFS)
  • Don't return visited but just the first node verifying a constraint and you check whether you can reach a set

You get pathfinding with just a small addition: store for each node the node they come from:

fn find_path(from: Node, to: Node) -> Option<Vec<Node>> {
    let mut todo = VecDeque::from([from]);
    // Act as both the 'visited' set and the history tracker
    let mut came_from: HashMap<Node, Node> = HashMap::new();

    while let Some(current) = todo.pop_front() {
        if current == to {
            // Reconstruct the path at the very end
            let mut path = vec![current];
            while let Some(&parent) = came_from.get(path.last().unwrap()) {
                path.push(parent);
            }
            path.reverse();
            return Some(path);
        }

        for neighbour in neighbours_of(current) {
            if neighbour != from && !came_from.contains_key(&neighbour) {
                came_from.insert(neighbour, current);
                todo.push_back(neighbour);
            }
        }
    }
    None
}

Replace the queue with a binary heap to first search the nodes estimated closest to your target and you have A*.

Notice how it's still a linear operation, how you could add tests, pause, or even store the search state ?

The core approach

The core of the approach isn't just stacks, and queues, and binary heaps, it's the reification of the execution frontier, converting temporal execution into just data, making it manageable, pausable, and easier to reason with.

With some habit of thinking this way, a whole world of problems becomes easy to solve, not with CS algorithms you're copying from a book but naturally and with all the constraints of real world problems.

I only mentioned graphs here, but you encounter the exact same architectural stakes with recursive descent parsers, regular expression engines (which can be re-engineered into explicit automata), or game behavior trees. Whenever you turn execution flow into data, your system becomes inherently controllable, testable, and actionable.