using arrays in a functional way

Source: Internet
Author: User using arrays in a functional way

Let's look at an example of F #, an important high-order function of two F # libraries working with arrays, and then implement the same functionality in C #. The script in Listing 10.12 first initializes an array with a random number, and then calculates their squares.

Listing 10.12 functional methods for working with arrays (F # Interactive)

> Let rnd = new System.Random ();

Val Rnd:System.Random

> Let numbers = Array.init 5 (fun _-> rnd.   Next (10));; [1]

Val numbers:int array = [| 0; 7; 2; 2|]

> Let squares = Numbers |> Array.map (fun N-(n, N*n));; [2]

Val squares: (int * int) array = [| ... |]

> For sq in Squares do | outputting tuples from the result array

printf "%A" sq;; |

(1, 1) (0, 0) (7, 49) (2, 4) (2, 4)

The first high-order function we use is array.init [1], similar to the List.int discussed in Listing 10.2, which initializes the array with the given function, and the second function is Array.map [2], the same function as the List.map function we are familiar with, In this example, we use it to create a tuple array, and each element of the result contains the original integer and its square.

The point is, in this case, we didn't use the assignment operator in the entire code. The first operation constructs a new array, and the second operation does not modify the array, but instead returns another newly created array. Although arrays are mutable, we use higher-order functions in our code to handle them without changing them at all. If we use a functional list, this example will work as well.

Select between arrays and lists

As we've seen, arrays and lists are used in a similar way, so there's a question of when to choose which one. The 1th consideration is whether the type is mutable. Function programming strongly emphasizes that data types are immutable, and we will see in the next and 14th chapters A practical example of why this is worthwhile. We are able to work with arrays in a functional way, but the list is stronger in terms of guaranteeing the correctness of the program.

Another thing to consider is that for some operations, one data type is easier or more efficient than another data type. Appending an element to the front of the list is easier than copying the contents of the array to a slightly larger new array. On the other hand, arrays are better for random access. Manipulating arrays is often faster. We can look at a simple example of using the #time directive:

Let L = [1:100000]

Let A = [| 1.. 100000 |];;

For I in 1.. Do? Takes 885ms

Ignore (l |> list.map (n-N));

For I in 1.. Do? Takes 109ms

Ignore (a |> array.map (fun n, N));

Arrays are usually better if you need to handle large datasets efficiently. In most cases, the primary purpose should be to use clear and simple code, and functional lists are generally more readable.

Our previous example shows that although you can use some of the basic operations provided on the array, you will often want to write something similar for yourself. Listing 10.13 is a function that handles an array in a function style: The parameter is an array, the input is computed and a new array is returned. This function is commonly used for "smooth" or "fuzzy" value arrays, where each value in the new array corresponds to the original value and the value on either side of it.

Listing 10.13 functional methods for blurring arrays (F #)

Let Blurarray (arr:int[]) =

Letres = Array.create arr. Length 0

Res.[0] <-(arr.[0] + arr.[1])/2 | [1]

Res.[arr. Length-1] <-(Arr.[arr. Length-2] + Arr.[arr. LENGTH-1])/2 |

For Iin 1: Arr. Length-2 do [1]

Res.[i] <-(arr.[i-1] + arr.[i] + arr.[i+1])/3


The function first creates an array that stores the results, the same size as the input array, and then calculates the value of the first element of the new array and the value of the last element [1] (which is the average of two elements), and the values are separated from the rest of the array because they are boundaries, and the pattern is not the same as the rest; Iterates through the elements in the middle of the array, taking the average of three values, and writing them as results into a new array.

The function internally uses the mutable pattern (mutation), at the beginning, the created array is populated with 0, and later, the computed value is written to the array. This variability is invisible from the outside, and when the caller is able to use the array, we have completed the change. When we use this function, we can safely use all the usual function techniques:

> Let AR = Array.init ten (fun _->rnd.  Next (20));; ? Initializing a random array

Val Ar:int [] = [|14; 14; 4; 16; 1; 15;5; 14; 7; 13|]

> ar |> blurarray;; ? Blurs an array once

Val It:int [] = [|14; 10; 11; 7; 10; 7;11; 8; 11; 10|]

> ar |> blurarray |> blurarray|> Blurarray; ? Use a pipe to obfuscate an array three times

Val It:int [] = [|7; 8; 9; 9; 9; 9; 9; 9;8; 8|]

The type of the Blurarray function is int[] and int[], which makes it composable. For the second command, we use the pipe operator to send the randomly generated array as input to the function, and the F # Interactive console automatically outputs the results. The last command shows that we are also able to call functions several times, the same way, we used the map or filter operation on the list.

We may want to extend this example to work with images and convert the Blurarray function into a real blur filter that can handle bitmaps. If you want to try it, you also need to use the Array2D module, which has functions for working with two-dimensional arrays, and. NET bitmap classes that read and write graphics data, such as GetPixel and SetPixel. To the 14th chapter, we will come back to this issue and discuss the use of parallelization to perform operations more efficiently.

After seeing the graceful use of arrays in F #, we will focus our attention back in C #. All C # Programmers know the basics of using arrays, and what we're interested in is the ability to write C # code that handles arrays using a function style. using arrays in a functional way

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.