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

Compartir libro
  1. 249 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

Hands-On Functional Programming in Rust

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

Andrew Johnson

Detalles del libro
Vista previa del libro
Índice
Citas

Información del 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

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Hands-On Functional Programming in Rust un PDF/ePUB en línea?
Sí, puedes acceder a Hands-On Functional Programming in Rust de Andrew Johnson en formato PDF o ePUB, así como a otros libros populares de Computer Science y Programming in C++. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Año
2018
ISBN
9781788831581
Edición
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...

Índice