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

Condividi libro
  1. 249 pagine
  2. English
  3. ePUB (disponibile sull'app)
  4. Disponibile su iOS e Android
eBook - ePub

Hands-On Functional Programming in Rust

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

Andrew Johnson

Dettagli del libro
Anteprima del libro
Indice dei contenuti
Citazioni

Informazioni sul libro

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

Domande frequenti

Come faccio ad annullare l'abbonamento?
È semplicissimo: basta accedere alla sezione Account nelle Impostazioni e cliccare su "Annulla abbonamento". Dopo la cancellazione, l'abbonamento rimarrà attivo per il periodo rimanente già pagato. Per maggiori informazioni, clicca qui
È possibile scaricare libri? Se sì, come?
Al momento è possibile scaricare tramite l'app tutti i nostri libri ePub mobile-friendly. Anche la maggior parte dei nostri PDF è scaricabile e stiamo lavorando per rendere disponibile quanto prima il download di tutti gli altri file. Per maggiori informazioni, clicca qui
Che differenza c'è tra i piani?
Entrambi i piani ti danno accesso illimitato alla libreria e a tutte le funzionalità di Perlego. Le uniche differenze sono il prezzo e il periodo di abbonamento: con il piano annuale risparmierai circa il 30% rispetto a 12 rate con quello mensile.
Cos'è Perlego?
Perlego è un servizio di abbonamento a testi accademici, che ti permette di accedere a un'intera libreria online a un prezzo inferiore rispetto a quello che pagheresti per acquistare un singolo libro al mese. Con oltre 1 milione di testi suddivisi in più di 1.000 categorie, troverai sicuramente ciò che fa per te! Per maggiori informazioni, clicca qui.
Perlego supporta la sintesi vocale?
Cerca l'icona Sintesi vocale nel prossimo libro che leggerai per verificare se è possibile riprodurre l'audio. Questo strumento permette di leggere il testo a voce alta, evidenziandolo man mano che la lettura procede. Puoi aumentare o diminuire la velocità della sintesi vocale, oppure sospendere la riproduzione. Per maggiori informazioni, clicca qui.
Hands-On Functional Programming in Rust è disponibile online in formato PDF/ePub?
Sì, puoi accedere a Hands-On Functional Programming in Rust di Andrew Johnson in formato PDF e/o ePub, così come ad altri libri molto apprezzati nelle sezioni relative a Computer Science e Programming in C++. Scopri oltre 1 milione di libri disponibili nel nostro catalogo.

Informazioni

Anno
2018
ISBN
9781788831581
Edizione
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...

Indice dei contenuti