soma.cell

Basic examples

97 small Soma programs, from hello world to a full application, each commented line by line and run when this page was built. Read them in order to learn the language; the verified corpus has the larger programs.

#ExampleWhat it shows
001Hello WorldThe simplest Soma program: a cell with one handler that prints a greeting.
002Variables and AssignmentDemonstrates let bindings, reassignment, and string interpolation.
003Basic TypesSoma has these built-in types: Int, Float, String, Bool, List, Map, and () () is null/unit. type_of() tells you what something is.
004Arithmetic OperationsDemonstrates +, -, *, /, % on integers and floats.
005String OperationsDemonstrates Soma's rich set of string built-in functions.
006String InterpolationSoma strings support {variable} interpolation, including map field access.
007Null Handling() is null in Soma. The ?? operator provides defaults for null values.
008Type ConversionsDemonstrates to_string(), to_int(), to_float(), and to_json()/from_json().
009Booleans and ComparisonsDemonstrates boolean values and comparison operators.
010Multiple HandlersA cell can have multiple handlers. Each is like a public method. Handlers can call each other.
011If / ElseDemonstrates conditional branching with if/else.
012While LoopsDemonstrates the while loop for repeated execution.
013For..In Loopsfor..in iterates over List values.
014RecursionHandlers can call themselves recursively.
015Nested Conditions and Complex LogicDemonstrates deeply nested if/else for multi-factor decisions.
016Loop PatternsCommon loop patterns: accumulator, find, early exit simulation.
017FizzBuzzThe classic interview problem, implemented in Soma.
018String Builder PatternDemonstrates building strings with += (append) and concat.
019Number AlgorithmsClassic number theory: GCD, primality test, collatz sequence.
020Iterating Over MapsMaps are iterated via .keys(), then accessing each value with .get().
021List BasicsCreating lists, accessing elements, appending, and getting length.
022Map BasicsCreating maps, accessing fields, and using with/without/merge.
023Nested Data StructuresLists of maps, maps of lists — complex nested data.
024List TransformationsBuilding new lists from existing ones with for loops.
025Flatten and Zipflatten() merges nested lists; zip() pairs up two lists.
026Enumerateenumerate() adds an index to each element of a list.
027Pluck and Selectpluck() extracts a single field; select() picks multiple fields.
028JSON Serializationto_json() and from_json() for data serialization.
029Memory SlotsCells can have persistent memory using the memory { } block. Memory slots have properties like [persistent, consistent].
030Collection AlgorithmsHigher-level operations: group_by, unique counting, frequency analysis.
031Filter and Sort Pipelinesfilter_by() and sort_by() are the building blocks of data pipelines.
032The Pipe Operator |>a |> f(b) is equivalent to f(a, b). Enables readable data pipelines.
033Joining Datasetsjoin() and left_join() combine two lists on a shared key.
034Aggregation with agg()agg() groups by a field and computes aggregates (sum, avg, count, etc).
035Sum, Avg, Min, MaxConvenience aggregation functions that work on a whole list.
036Group Bygroup_by() partitions data; combine with iteration for analytics.
037Multi-Stage PipelineChaining multiple operations: filter -> join -> aggregate -> sort.
038Top N Analysistop() takes the first N rows from a (usually sorted) list.
039Sales Dashboard PipelineA realistic multi-table analytics pipeline for sales data.
040ETL Pipeline (Extract, Transform, Load)Simulates an ETL workflow: extract raw data, transform it, load a summary.
041Simple REST APIA minimal key-value API with put, get, delete. Serve: soma serve 041_simple_api.cell Test: curl localhost:8080/put/mykey/myvalue curl loca
042CRUD API for UsersFull Create-Read-Update-Delete API using JSON serialization. Serve: soma serve 042_crud_api.cell Test: curl -X POST localhost:8080/create?
043JSON API ResponsesDemonstrates returning structured JSON from API handlers.
044HTTP Status Codesresponse() lets you set HTTP status codes for error handling. Serve: soma serve 044_status_codes.cell Test: curl localhost:8080/find/1 -
045Input ValidationValidates input data and returns appropriate error responses.
046Generic Request HandlerThe special request(method, path, body) handler catches all HTTP requests. Serve: soma serve 046_request_handler.cell Test: curl localhost
047Bookmarks APIA practical API for managing bookmarks with tags.
048Search APIFilter and search through data using pipeline operators.
049Counter APIA simple counter with increment, decrement, and get. Demonstrates memory slots and basic state management. Serve: soma serve 049_counter_ap
050Notes API with SearchA notes API that supports creating, listing, and searching notes.
051Static HTML Pagehtml() wraps content with the correct content-type for browsers. Use single quotes for HTML attributes (double quotes delimit Soma strings).
053HTML Form HandlingForms submit to signal handlers. GET forms use query parameters. Serve: soma serve 053_html_form.cell Test: open http://localhost:8080 ->
054HTMX CounterA counter that updates without page reloads using HTMX. Serve: soma serve 054_htmx_counter.cell Test: open http://localhost:8080
057Redirectsredirect() sends an HTTP redirect response to the browser. Serve: soma serve 057_redirect.cell Test: curl localhost:8080/old-page -> redir
058HTML Partials (Component Pattern)Break HTML into reusable handler-based components.
059Multi-Page App with RoutingRoute different paths to different pages using the request handler. Serve: soma serve 059_multi_page.cell Test: curl localhost:8080/
060Dashboard Page with Dynamic DataCombines data processing with HTML rendering for a dashboard.
061Basic State MachineState machines define valid transitions. The compiler enforces them.
062Ticket Tracking SystemA support ticket system with state machine for ticket lifecycle.
063Approval WorkflowA multi-stage approval process using state machines.
064Document LifecycleDocuments move through draft -> review -> published states.
065E-Commerce Order PipelineFull order management: create, add items, process through stages.
066Deployment PipelineCI/CD deployment stages modeled as a state machine.
067Kanban Task BoardTasks flow through: backlog -> todo -> in_progress -> done.
068Subscription LifecycleModels a SaaS subscription: trial -> active -> cancelled etc.
069Interview ProcessCandidate moves through interview stages.
070Querying Valid Transitionsvalid_transitions() returns what states are reachable from the current one.
071CSV-Like Data ProcessingParse and process tabular data represented as lists of maps.
072Analytics ReportMulti-dimensional analytics on a dataset.
073Report GeneratorBuilds a formatted text report from data.
074Data CleaningClean and normalize messy data.
075Pivot TableSummarize data across two dimensions (like a pivot table).
076Text HistogramBuild a simple text-based histogram from data.
077Moving AverageCompute a simple moving average over a series of values.
078LeaderboardProcess game scores into a ranked leaderboard.
079Data Merge (Multi-Source Join)Combine data from multiple sources using joins.
080ETL Transformation PipelineExtract data, apply multiple transformations, produce final output.
081Blog EngineA simple blog with posts and listing.
082Contact BookManage contacts with search capability.
083Inventory ManagementTrack products, quantities, and stock levels.
084Invoice GeneratorCreate invoices with line items and compute totals.
085Task TrackerA project task tracker with priorities and assignment.
086Expense TrackerTrack expenses by category and generate summaries.
087Quiz ScoringScore a quiz and provide a grade.
088Recipe BookStore and search recipes with ingredients.
089URL ShortenerShorten URLs and track visit counts. Serve: soma serve 089_url_shortener.cell
090Polling / Voting SystemCreate polls, cast votes, see results.
091BigInt ArithmeticBigInt provides arbitrary-precision integers — no overflow.
092Basic TestsTests are declared with `cell test Name { rules { assert ... } }`.
093Testing String FunctionsTest string manipulation with declarative assertions.
094Testing Recursive FunctionsVerify recursive algorithms with declarative tests.
095Face Block and PromisesThe face block declares a cell's public interface and promises. Promises are runtime-checked guarantees.
096Custom PropertiesDefine custom properties that extend the memory system. The language grows — no compiler changes needed.
097Memory PropertiesMemory slots can have different property combinations that declare durability, consistency, and visibility semantics.
098Multiple Cells in One FileA file can contain multiple cells. Each is an independent unit. Tests can reference handlers from non-test cells.
099Comprehensive Example: Employee DirectoryCombines multiple Soma features in one realistic application: - Memory with properties - Data pipelines with filter/sort/aggregate - String
100Full Application: Product Catalog with State MachineThe capstone example: combines cells, state machines, pipelines, memory, tests, and HTML rendering in one file.