Leanpub Header

Skip to main content

OCaml Artificial Intelligence Cook Book

OCaml Artificial Intelligence Cook Book
This book is 100% completeLast updated on 2026-10-12
Free With Membership

With Membership

Free!

$10.00

You pay

Author earns

$

Also available for 1 book credit with a Reader Membership

PDF
EPUB
WEB
APP
About

About

About the Book

Most AI books hand you a Python library and a model you can't see inside. This book has you build the machinery yourself, in OCaml. You will write a neural network that learns from scratch, with backpropagation you can read line by line. You will also write a SPARQL query engine in about 70 lines and a Go engine that plays thousands of games in parallel across every core of your laptop. Chapters on LLM clients cover Ollama, OpenAI and Gemini, with JSON codecs you can test offline without an API key. Every example is a small, complete program that you can run, test and change today.

OCaml suits this work well. Its type system catches most mistakes before your code runs, so a program that compiles usually works. OCaml 5 adds two features that most languages still lack: effect handlers, which let ordinary code carry state without monads, and domains, which run work on all your CPU cores at once. This book shows both in real AI code, alongside classic techniques: part-of-speech tagging, symbolic math, RDF knowledge graphs, web scraping, and game-playing agents.

You don't need to know OCaml already. Chapter 1 teaches the parts of the language the book uses, and after that you can read the chapters in any order. The 29 example projects each build with one command and come with their own tests. I have written AI software since the 1980s, at companies including SAIC, Mind.ai, Google and Capital One. This book collects the small, sharp tools I reach for most, written so that you can understand every line and make them your own.

Share this book

Author

About the Author

Mark Watson

Mark Watson is a consultant specializing in LLMs, deep learning, machine learning, knowledge graphs, and general artificial intelligence software development. He uses Common Lisp, Clojure, Python, Java, Haskell, and Ruby for development.

He is the author of 20+ published books on Artificial Intelligence, Deep Learning, Java, Ruby, Machine Learning, Common LISP, Clojure, JavaScript, Semantic Web, NLP, C++, Linux, and Scheme. He has 55 US Patents.

Mark's consulting customer list includes: Google, Capital One, Olive AI, CompassLabs, Disney, Sitescout.com, Embed.ly, and Webmind Corporation.

Mark wrote ten traditional published books for McGraw Hill, Springer Verlag, J Wiley, and Morgan Kaufman publishers before adopting the LeanPub self-publishing platform.

The Leanpub Podcast

Podcast

Podcast Episode

Contents

Table of Contents

Preface

  1. The Example Programs
  2. How to Read This Book
  3. Setup
  4. License for the Book Manuscript: Creative Commons
  5. Hire the Author as a Consultant
  6. A Short Note on My AI Journey
  7. Acknowledgements

A Quick OCaml Tutorial

  1. Installing OCaml and the Tools
  2. A First Program
  3. The REPL
  4. Pattern Matching and Recursion
  5. if / then / else Is an Expression
  6. Branching and Option Values
  7. match Expressions
  8. let Bindings for Local Values
  9. Composing and Applying Functions
  10. The Map Functor
  11. Variant Types and a Custom Order
  12. Tutorial Wrap Up

Functional Patterns: State, Laziness, Timing, and Debugging

  1. A State Module
  2. The Same State with Effect Handlers
  3. Lazy Sequences and Trace Debugging
  4. Timing and Timeouts

Input/Output and Command-Line Applications

  1. Reading a Whole File
  2. Mapping Over the Result of a Read
  3. Words Two Files Share
  4. Reading From the Console
  5. An Interactive Loop
  6. A Guessing Game With State
  7. Handling a Missing File
  8. Running the Examples

Testing OCaml Code with Alcotest

  1. Project Layout: Library, Program, and Tests
  2. The Interface File
  3. The Implementation
  4. Writing Tests
  5. Running the Suite

Symbolic Mathematics

  1. Exact Rationals
  2. Modeling the Math
  3. Polynomials and Normalization
  4. Evaluating a Polynomial
  5. Differentiation
  6. Integration and Definite Integrals
  7. Running It

Text Processing and DataFrames

  1. Cleaning Free Text
  2. Reading CSV
  3. Round-Tripping JSON
  4. A Small DataFrame
  5. The Housing Analysis
  6. Running It

Natural Language Processing

  1. A Part-of-Speech Tagger
  2. An NLP Toolkit

SQLite Databases

  1. Typed Queries
  2. Running a Query
  3. Lwt and Threading Results
  4. Opening the Connection
  5. Building and Running

RDF Data Stores and SPARQL Queries

  1. Modeling Triples and Queries
  2. Matching a Pattern
  3. The Join
  4. Running Queries as Data
  5. Parsing SPARQL Text
  6. Querying DBpedia Over HTTP
  7. Running Both

Web Scraping

  1. Parsing HTML
  2. Fetching a Page
  3. Putting It Together
  4. Running It

Networking and Web Applications

  1. A TCP Server and Client
  2. Web Applications with Dream
  3. A Web View With a JavaScript Bridge
  4. A Chat App Backed by Gemini

Using Large Language Model APIs

  1. A Local Ollama Client
  2. An OpenAI Chat Client
  3. A Gemini Client
  4. Entity Extraction With a Model
  5. Running the Clients

Search APIs: Brave Search

  1. Modeling a Result
  2. Decoding Optional Fields
  3. Formatting a Result
  4. The HTTP Call
  5. Running It

Knowledge Graph Creator

  1. The Pipeline
  2. Reading Input
  3. Generating RDF Triples
  4. Generating Neo4j Cypher
  5. Batch Processing
  6. Running It

AI for Games

  1. Blackjack
  2. Contract Bridge
  3. Go

Neural Networks from Scratch

  1. The Network
  2. The Forward Pass
  3. Measuring Error
  4. Backpropagation
  5. Training
  6. Learning XOR
  7. A Curved Boundary
  8. Testing a Network
  9. Where to Go Next

Conclusions

Also by the Author

Also by the Author

The Leanpub 60 Day 100% Happiness Guarantee

Within 60 days of purchase you can get a 100% refund on any Leanpub purchase, in two clicks.

See full terms...

Earn $8 on a $10 Purchase, and $16 on a $20 Purchase

We pay 80% royalties on purchases of $7.99 or more, and 80% royalties minus a 50 cent flat fee on purchases between $0.99 and $7.98. You earn $8 on a $10 sale, and $16 on a $20 sale. So, if we sell 5000 non-refunded copies of your book for $20, you'll earn $80,000.

(Yes, some authors have already earned much more than that on Leanpub.)

Learn more about writing on Leanpub

Free Updates. DRM Free.

If you buy a Leanpub book, you get free updates for as long as the author updates the book! Many authors use Leanpub to publish their books in-progress, while they are writing them. All readers get free updates, regardless of when they bought the book or how much they paid (including free).

Most Leanpub books are available in PDF (for computers) and EPUB (for phones, tablets and Kindle). The formats that a book includes are shown at the top right corner of this page.

Finally, Leanpub books don't have any DRM copy-protection nonsense, so you can easily read them on any supported device.

Learn more about Leanpub's ebook formats and where to read them

Write and Publish on Leanpub

You can use Leanpub to easily write, publish and sell in-progress and completed ebooks and online courses!

Leanpub is a powerful platform for serious authors, combining a simple, elegant writing and publishing workflow with a store focused on selling in-progress ebooks.

Leanpub is a magical typewriter for authors: just write in plain text, and to publish your ebook, just click a button. (Or, if you are producing your ebook your own way, you can even upload your own PDF and/or EPUB files and then publish with one click!) It really is that easy.

Learn more about writing on Leanpub