Declarative programming in Rust

Pascal Hertleif

2018-09-05

Hi, I’m Pascal Hertleif

What is a computer program?

To make a program work,

  • you tell a computer what to do,
  • in tiny steps, specific instructions.
  • This is imperative.
  • Hard to reason about the general behavior of a program

“This is RustFest, Pascal, not AssemblyCamp”

Maintainable code

Is my code maintainable?

  1. How much do I need to read to understand what’s going on?
  2. How much do I need to write to make a change?
  3. How easy is it to identify the core concepts?

What is ‘Declarative Programming’

Declarative programming is often defined as any style of programming that is not imperative.

Wikipedia

What instead of How

  • Don’t write down all the steps how to get somewhere
  • Express what you want to accomplish

How?

  • Identify concepts and extract their behavior
  • Abstract over control flow
  • Compose your application from smaller pieces

Get to the point

Declarative code in Rust

By example

Loops

Find the first element that ends with “m”

New requirements! Find up to 5 elements that end with “m”

Iterators

Another iterator example

Is there an item that starts with “l”?

Parse JSON

{"a": 4}

First try

New requirements!

This structure now has three fields

Derive it.

Command Line Arguments

Plain old std

New requirements: Flags

tool -o Output.file Input.file

Clap

Isn’t this a data structure, too?

Generic, type-driven behavior

Huh?

We write generic functions.

The concrete types will declare what the user wants

Read JSON data from a HTTP request

Extractors

Be aware of your magic budget

“Any sufficiently high abstraction is indistinguishable from magic.”

Monads

“This is RustFest, Pascal, not Haskell Symposium”

What is magic?

Code whose behavior is hard to predict (or remember)

  • Unfamiliar macros
  • Very generic code
  • But also: Very concise and ‘clever’ code

You can turn that magic into science, using the right tools

e.g. using cargo expand

That often only moves the complexity but doesn’t resolve it

How to teach this?

  • Interactive learning: Clippy lints
  • Write libraries that provide easy to use abstractions
  • Give an introductory talk on it (👋)

Thank you!

Have a great lunch!

I’m Pascal and I want you to talk to me!

{twitter,github}.com/killercup

Slides: git.io/declarative-programming-in-rust