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

Published on 12 May 2024 09:40 PM

How to resolve the algorithm First-class functions step by step in the Scala 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 Scala programming language

Source code in the scala programming language

import math._

// functions as values
val cube = (x: Double) => x * x * x
val cuberoot = (x: Double) => pow(x, 1 / 3d)

// higher order function, as a method
def compose[A,B,C](f: B => C, g: A => B) = (x: A) => f(g(x))

// partially applied functions in Lists
val fun = List(sin _, cos _, cube)
val inv = List(asin _, acos _, cuberoot)

// composing functions from the above Lists
val comp = (fun, inv).zipped map (_ compose _)

// output results of applying the functions
comp foreach {f => print(f(0.5) + "   ")}


  

You may also check:How to resolve the algorithm Atomic updates step by step in the BBC BASIC programming language
You may also check:How to resolve the algorithm Aliquot sequence classifications step by step in the Elixir programming language
You may also check:How to resolve the algorithm Tree traversal step by step in the Coq programming language
You may also check:How to resolve the algorithm Loops/Infinite step by step in the 68000 Assembly programming language
You may also check:How to resolve the algorithm Include a file step by step in the 68000 Assembly programming language