frontpage.
newsnewestaskshowjobs

Made with ♥ by @iamnishanth

Open Source @Github

fp.

Open in hackernews

Building a symbolic math REPL in C

https://github.com/marcomit/derive.c
1•marcomit•1h ago

Comments

marcomit•1h ago
I spent a few days building this small and simple derivation engine.

``` >> f = x^3 + 2x x^3 + 2 x

>> f'(x) 3 * x^2 + 2

>> f'(x)'(x) 6 * x ```

Note: the simplifier isn't perfect. Some results may be messier than they should. But the core works.

--- ### Representing expressions Everything in this program is an `expr`. A number, a variable, `sin(x)`, `x^2+1`. All the same struct

```c typedef struct expr { exprtype type; int mindepth, maxdepth, nodes; int ref; union { char symbol; double num; struct { struct expr left; struct expr right; }; struct expr unary; }; } expr; ``` The union is the interesting part Depending on the type, an epxression is either: - a leaf: just a number or a symbol (x, 3.14) - a unary: just one child (sin(x), -x, log(x)) - a binary: just two children (x+1, x^2)

So the expression `x^2+1` becomes a tree like this: ``` ADD / \ EXP 1 / \ x 2 ``` Every node is the same struct. You navigate it recursively. This pattern shows up everywhere in the codebase. ---

--- ### Differentiation Symbolic differentiation is just pattern matching on the expression tree. Each node type has a rule, and you apply it recursively. The main function is a switch: ``` expr derive(expr f, expr sym) { switch (f->type) { case EXPR_ADD: return deriveAdd(f, sym); case EXPR_MUL: return deriveMul(f, sym); case EXPR_EXP: return deriveExp(f, sym); case EXPR_SIN: return deriveSin(f, sym); case EXPR_LOG: return deriveLog(f, sym); case EXPR_SYM: return eq(f, sym) ? one : zero; case EXPR_NUM: return zero; // ... } } ``` The base cases are trivial: the derivative of a constant is zero and the derivative of x with respect to x is one (anything else is zero).

The interesting cases are the rules. Here's the product rule: ``` expr

deriveMul(expr f, expr sym) { expr left = mul(derive(f->left, sym), retain(f->right)); expr right = mul(retain(f->left), derive(f->right, sym)); return add(left, right); } ``` That's literally `f' * g + f * g'`. The `retain` calls are there because we're sharing the original subtrees, the derivative will own a reference to them. The chain rule falls out naturally too. When you differentiate `sin(x^2)`, `deriveSin` calls `derive` on its argument, which recurses into the `x^2`subtree. You don't write chain rule handling separately, it's just recursion.

--- ### Simplification Differentiation produces correct but messy results. `derive(x^2)` gives you `x^2 * (1 * log(x) + 2 * 1 / x)` before any cleanup. Simplification is a second recursive pass over the tree that applies algebric identities. Some cases are straightforward: ``` x * 0 = 0 1 * x = x x / x = 1 x^1 = x x^0 = 1 ... ``` The simplifier recurses bottom-up: it simplifies the children first, then applies rules to the result. This is also where the "not perfect" disclaimer comes in. Simplification is essentially rewriting, and you can always find expressions that don't reduce as far as they could. Getting it fully right would mean implementing a proper term rewritiing system, which is a rabbit hole I chose not to go down.

--- ### The parser The REPL reads a string and turns it into an expression tree. This is done with hand-written recursive descendant parser, no lexer generator, no parser library.

The grammar looks like this (there's actually a comment in the source): ``` unary = num | sym | "-" unary | "(" expr ")" postfix = unary ("^" unary | "'(" sym ")" | "(" sym "=" num ")")* factor = postfix (("" | "/") postfix) term = factor (("+" | "-") factor)* expr = term | sym "=" expr ``` --- If you want to know more about the implementation you can check the full blog post here: [derive.c](https://marcomit.it/derive.c)

The Authority of Thought

https://harpers.org/archive/2026/04/the-authority-of-thought-pankaj-mishra/
1•jbegley•31s ago•0 comments

A New Global Botnet (Jackskid) Generating Tbps of DDoS

https://github.com/deepfield/public-research/blob/main/jackskid/report.md
1•lakoshi•41s ago•0 comments

I Started with Repairs

https://posts.joedmin.cz/posts/how-i-started-with-repairs/
1•lapity_lapoty•1m ago•0 comments

Nix Module for Wrapping Packages

https://github.com/BirdeeHub/nix-wrapper-modules
1•xavwe•2m ago•0 comments

Electricity is eating the world. Is it time for an American Shenzhen?

https://www.darkmatter.blog/articles/electricity-is-eating-the-world-is-it-time-for-an-american-s...
1•jbegley•2m ago•0 comments

The Dark Matter of Hardware Engineering

https://darkmatter.blog/articles/dark-matter-of-hardware
1•jbegley•3m ago•0 comments

Board games, cognitive decline and dementia

https://pmc.ncbi.nlm.nih.gov/articles/PMC3758967/
1•RickJWagner•6m ago•0 comments

Show HN: Forecast Planner, personal finance app that forecasts instead of tracks

https://www.forecast-planner.com/
1•curiousweb•7m ago•0 comments

From Chile to the Philippines, meet the people pushing back on AI

https://restofworld.org/2026/ai-pushback-chile-mexico-kenya-philippines/
2•Brajeshwar•7m ago•0 comments

Unified RISC-V IP Access Platform

https://openhwgroup.github.io/uap/
1•Tomte•9m ago•0 comments

Secure Domain Name System (DNS) Deployment 2026 Guide [pdf]

https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-81r3.pdf
1•XzetaU8•9m ago•0 comments

Game Devs Reveal All Their Ugly Placeholder Assets Made Without AI

https://kotaku.com/crimson-desert-ai-art-placeholder-game-devs-share-assets-images-genai-2000681053
2•cainxinth•10m ago•0 comments

Vulkanised 2026 talks now available (playlist)

https://www.youtube.com/playlist?list=PLMLurvdlOpWNFlPD0kumIYtivIpUx1V0a
2•pjmlp•12m ago•0 comments

Hung cron jobs: what causes them and how to detect them without a sidecar

https://crontify.com/blog/hung-cron-jobs-detection
2•vincentabolarin•14m ago•0 comments

Static IPv4 address on outbound connections from a Cloud Run Job

https://omnitroid.bearblog.dev/giving-a-docker-container-a-static-ip-on-outbound-connections/
1•OmniTroid•15m ago•0 comments

LiteLLM PyPI has been compromised an hour ago, do not update

https://futuresearch.ai/blog/litellm-pypi-supply-chain-attack/
9•Bullhorn9268•17m ago•3 comments

Tell HN: Litellm 1.82.7 and 1.82.8 on PyPI are compromised

3•dot_treo•17m ago•0 comments

Cardputer-Adv (40€ ESP32-S3): Evil Portal and Deauth Attack, with/Without PMF

https://paolocostanzo.github.io/cardputer-adv-wifi-security/
1•PCostanzo•17m ago•0 comments

Designing a Python Language Server: Lessons from Pyre That Shaped Pyrefly

https://pyrefly.org/blog/lessons-from-pyre/
2•ocamoss•20m ago•0 comments

A Tom-Inspired Agenda for AI Safety Research

https://www.lesswrong.com/posts/2BFifEBfCCWtkGsTp/a-tom-inspired-agenda-for-ai-safety-research
2•joozio•21m ago•1 comments

God, I hate .env files

3•zidoo•22m ago•3 comments

How do you ensure consistency in test results generated via AI models?

1•allenmatthew•23m ago•0 comments

OpenAI offering Private Equity a return of 17.5% and early access to models

https://www.reuters.com/business/openai-sweetens-private-equity-pitch-amid-enterprise-turf-war-wi...
3•alecco•23m ago•3 comments

Mathematical framework maps landscape of student knowledge via short quizzes

https://phys.org/news/2026-03-mathematical-framework-landscape-student-knowledge.html
2•Brajeshwar•26m ago•0 comments

Show HN: Running AI agents across environments needs a proper solution

https://github.com/liquidos-ai/Odyssey
5•human_hack3r•27m ago•3 comments

Delve.co and SoC Type 2 Compliance Scandal and Audit

https://www.kaggle.com/datasets/dheerajmpai/delve-data-leaks
1•dheerajmp•27m ago•0 comments

Cortex – Local-first AI memory engine, beats Mem0 on LoCoMo, encrypted, free

3•gambletan•27m ago•1 comments

Show HN: Claude's Code – tracking the 19M+ commits generated by Claude on GitHub

https://www.claudescode.dev/
8•phantomCupcake•28m ago•0 comments

Turn any REST API into an MCP server. No code required

https://github.com/Work90210/APIFold
1•KyleFuehri•30m ago•0 comments

PetClaw: A Desktop Pet Companion That Works 24/7

https://petclaw.ai/
2•limoce•31m ago•0 comments