Hands-On Functional Programming in Rust
eBook - ePub

Hands-On Functional Programming in Rust

Build modular and reactive applications with functional programming techniques in Rust 2018

Andrew Johnson

Share book
  1. 249 pages
  2. English
  3. ePUB (mobile friendly)
  4. Available on iOS & Android
eBook - ePub

Hands-On Functional Programming in Rust

Build modular and reactive applications with functional programming techniques in Rust 2018

Andrew Johnson

Book details
Book preview
Table of contents
Citations

About This Book

Explore the support Rust offers for creating functional applications in Rust. Learn about various design patterns, implementing concurrency, metaprogramming, and so on in the processAbout This Book• Learn generics, organization, and design patterns in functional programming• Modularize your applications and make them highly reusable and testable using functional design patterns• Get familiar with complex concepts such as metaprogramming, concurrency, and immutabilityWho This Book Is ForThis book is for Rust developers who are comfortable with the language and now want to improve their coding abilities by learning advanced functional techniques to enhance their skillset and create robust and testable apps.What You Will Learn• How Rust supports the use of basic functional programming principles• Use functional programming to handle concurrency with elegance• Read and interpret complex type signatures for types and functions• Implement powerful abstractions using meta programming in Rust• Create quality code formulaically using Rust's functional design patterns• Master Rust's complex ownership mechanisms particularly for mutabilityIn DetailFunctional 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.Style and approachStep-by-step guide covering advanced concepts and building functional applications in Rust

Frequently asked questions

How do I cancel my subscription?
Simply head over to the account section in settings and click on “Cancel Subscription” - it’s as simple as that. After you cancel, your membership will stay active for the remainder of the time you’ve paid for. Learn more here.
Can/how do I download books?
At the moment all of our mobile-responsive ePub books are available to download via the app. Most of our PDFs are also available to download and we're working on making the final remaining ones downloadable now. Learn more here.
What is the difference between the pricing plans?
Both plans give you full access to the library and all of Perlego’s features. The only differences are the price and subscription period: With the annual plan you’ll save around 30% compared to 12 months on the monthly plan.
What is Perlego?
We are an online textbook subscription service, where you can get access to an entire online library for less than the price of a single book per month. With over 1 million books across 1000+ topics, we’ve got you covered! Learn more here.
Do you support text-to-speech?
Look out for the read-aloud symbol on your next book to see if you can listen to it. The read-aloud tool reads text aloud for you, highlighting the text as it is being read. You can pause it, speed it up and slow it down. Learn more here.
Is Hands-On Functional Programming in Rust an online PDF/ePUB?
Yes, you can access Hands-On Functional Programming in Rust by Andrew Johnson in PDF and/or ePUB format, as well as other popular books in Computer Science & Programming in C++. We have over one million books available in our catalogue for you to explore.

Information

Year
2018
ISBN
9781788831581
Edition
1

Performance, Debugging, and Metaprogramming

Writing fast efficient code can be something to be proud of. It also might be a waste of your employer's resources. In the performance section, we will explore how to tell the difference between the two and give best-practices, processes, and guidelines to keep your application slim.
In the debugging section, we offer tips to help find and resolve bugs faster. We also introduce the concept of defensive coding, which describes techniques and habits to prevent or isolate potential issues.
In the metaprogramming section, we explain macros and other features that are similar to macros. Rust has a fairly sophisticated metaprogramming system that allows the user or libraries to extend the language with automatic code generation or custom syntax forms.
In this chapter, we will learn the following:
  • Recognizing and applying good performant code practices
  • Diagnosing and improving performance bottlenecks
  • Recognizing and applying good defensive coding practices
  • Diagnosing and resolving software bugs
  • Recognizing and applying metaprogramming techniques

Technical requirements

A recent version of Rust is necessary to run the examples provided:
https://www.rust-lang.org/en-US/install.html
This chapter's code is available on GitHub:
https://github.com/PacktPublishing/Hands-On-Functional-Programming-in-RUST
Specific installation and build instructions are also included in each chapter's README.md file.

Writing faster code

Premature optimization is the root of all evil
– Donald Knuth
A good software design tends to create faster programs, while a bad software design tends to create slower programs. If you find yourself asking, "Why is my program slow?, then first ask yourself, Is my program disorderly?"
In this section, we describe some performance tips. These are generally good habits when programming in Rust that will coincidentally lead to improved performance. If your program is slow, then first check to see whether you are violating one of these principles.

Compiling with release mode

This is a really simple suggestion that you should know about if you are at all concerned about performance.
  • Rust normally compiles in debug mode, which is slow:
cargo build
  • Rust optionally compiles in release mode, which is fast:
cargo build --release
  • Here is a comparison using debug mode for a toy program:
$ time performance_release_mode
real 0m13.424s
user 0m13.406s
sys 0m0.010s
  • The following is the release mode:
$ time ./performance_release_mode
real 0m0.316s
user 0m0.309s
sys 0m0.005s
Release mode is 98% more efficient with regard to CPU usage for this example.

Doing less work

Faster programs do less. All optimization is a process of searching for work that doesn't need to be done, and then not doing it.
Similarly, the smallest programs fewer resources less. All space optimization is a process of searching for resources that don't need to be used, and then not using them.
For example, don't collect an iterator when you don't need the result, consider the following example:
extern crate flame;
use std::fs::File;

fn main() {
let v: Vec<u64> = vec![2; 1000000];

flame::start("Iterator .collect");
let mut _z = vec![];
for _ in 0..1000 {
_z = v.iter().map(|x| x*x).collect::<Vec<u64>>();
}
flame::end("Iterator .collect");

flame::start("Iterator iterate");
for _ in 0..1000 {
v.iter().map(|x| x * x).for_each(drop);
}
flame::end("Iterator iterate");

flame::dump_html(&mut File::create("flame-graph.html").unwrap()).unwrap();
}
Needlessly collecting the result of the iterator makes the code 27% slower compared to code that just drops the result.
Memory allocation is similar. Well-designed code preferring pure functions and avoiding side-effects will tend to minimize memory usage. In contrast, messy code can lead to old data hanging around. Rust memory safety does not extend to preventing memory leaks. Leaks are considered safe code:
use std::mem::forget;

fn main() {
for _ in 0..10000 {
let mut a = vec![2; 10000000];
a[2] = 2;
forget(a);
}
}
The forget function is seldom used. Similarly, memory leaks are permitted but sufficiently discouraged that they are somewhat uncommon. Rust memory management tends to be such that by the time you cause a memory leak you are probably waist-deep in other poor design decisions.
However, unsused memory is not uncommon. If you don't keep track of what variables you are actively using, then old variables will likely remain in scope. This is not the typical definition o...

Table of contents