Book Image

Hands-On Functional Programming in Rust

By : Andrew Johnson
Book Image

Hands-On Functional Programming in Rust

By: Andrew Johnson

Overview of this book

Functional programming allows developers to divide programs into smaller, reusable components that ease the creation, testing, and maintenance of software as a whole. Combined with the power of Rust, you can develop robust and scalable applications that fulfill modern day software requirements. This book will help you discover all the Rust features that can be used to build software in a functional way. We begin with a brief comparison of the functional and object-oriented approach to different problems and patterns. We then quickly look at the patterns of control flow, data the abstractions of these unique to functional programming. The next part covers how to create functional apps in Rust; mutability and ownership, which are exclusive to Rust, are also discussed. Pure functions are examined next and you'll master closures, their various types, and currying. We also look at implementing concurrency through functional design principles and metaprogramming using macros. Finally, we look at best practices for debugging and optimization. By the end of the book, you will be familiar with the functional approach of programming and will be able to use these techniques on a daily basis.
Table of Contents (12 chapters)

Using pure functions

Pure functions are the second technique that we recommend to prevent hard-to-reproduce bugs. Pure functions can be thought of as an extension of the avoid side-effects principle. The definition of a pure function is a function where the following is true:

  • No changes are caused outside of the function (no side-effects)
  • The return value does not depend on anything but the function parameters

Here are some examples of pure functions:

fn p0() {}

fn p1() -> u64 {
444
}

fn p2(x: u64) -> u64 {
x * 444
}

fn p3(x: u64, y: u64) -> u64 {
x * 444 + y
}

fn main()
{
p0();
p1();
p2(3);
p3(3,4);
}

Here are some examples of impure functions:

use std::cell::Cell;

static mut blah: u64 = 3;
fn ip0() {
unsafe {
blah = 444;
}
}

fn ip1(c: &Cell<u64>) {
c.set(333);
}

fn main()
{
ip0();
let r = Cell::new(3);
ip1(&r);
ip1(&r);
}

Rust does...