How to resolve the algorithm First-class functions step by step in the Rust programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm First-class functions step by step in the Rust programming language

Table of Contents

Problem Statement

A language has first-class functions if it can do each of the following without recursively invoking a compiler or interpreter or otherwise metaprogramming:

Write a program to create an ordered collection A of functions of a real number. At least one function should be built-in and at least one should be user-defined; try using the sine, cosine, and cubing functions. Fill another collection B with the inverse of each function in A. Implement function composition as in Functional Composition. Finally, demonstrate that the result of applying the composition of each function in A and its inverse in B to a value, is the original value. (Within the limits of computational accuracy). (A solution need not actually call the collections "A" and "B". These names are only used in the preceding paragraph for clarity.)

First-class Numbers

Let's start with the solution:

Step by Step solution about How to resolve the algorithm First-class functions step by step in the Rust programming language

Source code in the rust programming language

#![feature(conservative_impl_trait)]
fn main() {
    let cube      = |x: f64| x.powi(3);
    let cube_root = |x: f64| x.powf(1.0 / 3.0);

    let flist  : [&Fn(f64) -> f64; 3] = [&cube     , &f64::sin , &f64::cos ];
    let invlist: [&Fn(f64) -> f64; 3] = [&cube_root, &f64::asin, &f64::acos];

    let result = flist.iter()
                      .zip(&invlist)
                      .map(|(f,i)| compose(f,i)(0.5))
                      .collect::<Vec<_>>();

    println!("{:?}", result);

}

fn compose<'a, F, G, T, U, V>(f: F, g: G) -> impl 'a + Fn(T) -> V
    where F: 'a + Fn(T) -> U,
          G: 'a + Fn(U) -> V,
{
    move |x| g(f(x))

}


  

You may also check:How to resolve the algorithm Loops/Continue step by step in the Haxe programming language
You may also check:How to resolve the algorithm Compound data type step by step in the Oforth programming language
You may also check:How to resolve the algorithm Amb step by step in the Smalltalk programming language
You may also check:How to resolve the algorithm Count occurrences of a substring step by step in the MACRO-11 programming language
You may also check:How to resolve the algorithm GUI/Maximum window dimensions step by step in the Ada programming language