All lessons

Stacks

7 min · Elixir examples

Last-in-first-out structure for matching brackets, undo logic, and monotonic scans.

Elixir · Stacks0/5 cleared

Enemy 1 of 5

This code checks whether every opening bracket in a string has a matching closing bracket, using a stack to remember the opens. Press Run and look for the word valid in the output.

Why this works

A stack is like a pile of plates: you push on top and pop from the top. Elixir lists work great as a stack. Put a new item on the head with [item | stack], and pattern match [top | rest] = stack to pop it.

Classic use: walk a string of brackets and push opens; on a close, pop and check they match.

You
Syntax Skeleton
Loading editor…
Sign up to fightThis one runs on our servers, so it needs a free account.