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

Partager le livre
  1. 249 pages
  2. English
  3. ePUB (adapté aux mobiles)
  4. Disponible sur iOS et Android
eBook - ePub

Hands-On Functional Programming in Rust

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

Andrew Johnson

DĂ©tails du livre
Aperçu du livre
Table des matiĂšres
Citations

À propos de ce livre

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

Foire aux questions

Comment puis-je résilier mon abonnement ?
Il vous suffit de vous rendre dans la section compte dans paramĂštres et de cliquer sur « RĂ©silier l’abonnement ». C’est aussi simple que cela ! Une fois que vous aurez rĂ©siliĂ© votre abonnement, il restera actif pour le reste de la pĂ©riode pour laquelle vous avez payĂ©. DĂ©couvrez-en plus ici.
Puis-je / comment puis-je télécharger des livres ?
Pour le moment, tous nos livres en format ePub adaptĂ©s aux mobiles peuvent ĂȘtre tĂ©lĂ©chargĂ©s via l’application. La plupart de nos PDF sont Ă©galement disponibles en tĂ©lĂ©chargement et les autres seront tĂ©lĂ©chargeables trĂšs prochainement. DĂ©couvrez-en plus ici.
Quelle est la différence entre les formules tarifaires ?
Les deux abonnements vous donnent un accĂšs complet Ă  la bibliothĂšque et Ă  toutes les fonctionnalitĂ©s de Perlego. Les seules diffĂ©rences sont les tarifs ainsi que la pĂ©riode d’abonnement : avec l’abonnement annuel, vous Ă©conomiserez environ 30 % par rapport Ă  12 mois d’abonnement mensuel.
Qu’est-ce que Perlego ?
Nous sommes un service d’abonnement Ă  des ouvrages universitaires en ligne, oĂč vous pouvez accĂ©der Ă  toute une bibliothĂšque pour un prix infĂ©rieur Ă  celui d’un seul livre par mois. Avec plus d’un million de livres sur plus de 1 000 sujets, nous avons ce qu’il vous faut ! DĂ©couvrez-en plus ici.
Prenez-vous en charge la synthÚse vocale ?
Recherchez le symbole Écouter sur votre prochain livre pour voir si vous pouvez l’écouter. L’outil Écouter lit le texte Ă  haute voix pour vous, en surlignant le passage qui est en cours de lecture. Vous pouvez le mettre sur pause, l’accĂ©lĂ©rer ou le ralentir. DĂ©couvrez-en plus ici.
Est-ce que Hands-On Functional Programming in Rust est un PDF/ePUB en ligne ?
Oui, vous pouvez accĂ©der Ă  Hands-On Functional Programming in Rust par Andrew Johnson en format PDF et/ou ePUB ainsi qu’à d’autres livres populaires dans Computer Science et Programming in C++. Nous disposons de plus d’un million d’ouvrages Ă  dĂ©couvrir dans notre catalogue.

Informations

Année
2018
ISBN
9781788831581
Édition
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 des matiĂšres