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

Buch teilen
  1. 249 Seiten
  2. English
  3. ePUB (handyfreundlich)
  4. Über iOS und Android verfügbar
eBook - ePub

Hands-On Functional Programming in Rust

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

Andrew Johnson

Angaben zum Buch
Buchvorschau
Inhaltsverzeichnis
Quellenangaben

Über dieses Buch

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

Häufig gestellte Fragen

Wie kann ich mein Abo kündigen?
Gehe einfach zum Kontobereich in den Einstellungen und klicke auf „Abo kündigen“ – ganz einfach. Nachdem du gekündigt hast, bleibt deine Mitgliedschaft für den verbleibenden Abozeitraum, den du bereits bezahlt hast, aktiv. Mehr Informationen hier.
(Wie) Kann ich Bücher herunterladen?
Derzeit stehen all unsere auf Mobilgeräte reagierenden ePub-Bücher zum Download über die App zur Verfügung. Die meisten unserer PDFs stehen ebenfalls zum Download bereit; wir arbeiten daran, auch die übrigen PDFs zum Download anzubieten, bei denen dies aktuell noch nicht möglich ist. Weitere Informationen hier.
Welcher Unterschied besteht bei den Preisen zwischen den Aboplänen?
Mit beiden Aboplänen erhältst du vollen Zugang zur Bibliothek und allen Funktionen von Perlego. Die einzigen Unterschiede bestehen im Preis und dem Abozeitraum: Mit dem Jahresabo sparst du auf 12 Monate gerechnet im Vergleich zum Monatsabo rund 30 %.
Was ist Perlego?
Wir sind ein Online-Abodienst für Lehrbücher, bei dem du für weniger als den Preis eines einzelnen Buches pro Monat Zugang zu einer ganzen Online-Bibliothek erhältst. Mit über 1 Million Büchern zu über 1.000 verschiedenen Themen haben wir bestimmt alles, was du brauchst! Weitere Informationen hier.
Unterstützt Perlego Text-zu-Sprache?
Achte auf das Symbol zum Vorlesen in deinem nächsten Buch, um zu sehen, ob du es dir auch anhören kannst. Bei diesem Tool wird dir Text laut vorgelesen, wobei der Text beim Vorlesen auch grafisch hervorgehoben wird. Du kannst das Vorlesen jederzeit anhalten, beschleunigen und verlangsamen. Weitere Informationen hier.
Ist Hands-On Functional Programming in Rust als Online-PDF/ePub verfügbar?
Ja, du hast Zugang zu Hands-On Functional Programming in Rust von Andrew Johnson im PDF- und/oder ePub-Format sowie zu anderen beliebten Büchern aus Computer Science & Programming in C++. Aus unserem Katalog stehen dir über 1 Million Bücher zur Verfügung.

Information

Jahr
2018
ISBN
9781788831581

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...

Inhaltsverzeichnis