We can reset the value of the element of an array using the set
method. It only requires the index position of the element to reset and the new value.
Array.set arr n new_value
arr
: This is the array in which we want the value of one of its elements.n
: This is the index position of the element we want to reset its value.new_value
: This is the new value we want to use and replace the previous value of an element.The value returned is the element with a new value.
(*create some arrays*) let evenNumbers = [| 2; 4; 16; 8; 10;|];; let floatNumbers = [|3.111; 1.5;|];; let letters = [|'a'; 'm'; 'e'; 'y'; 'Z';|];; let fruits = [|"banana"; "apple"; "paw paw"; |];; (* reset some elements' values*) Array.set evenNumbers 2 6;; (* 16 will be changed to 6*) Array.set floatNumbers 0 3.5;; (* 3.111 will be changed to 3.5*) Array.set letters 4 'z';; (* 'Z' will be changed to 'z'*) Array.set fruits 1 "pine-apple";; (* "apple" will be changed to "pine-apple" *) (*access the elements to see changes*) print_int(evenNumbers.(2));; print_string("\n");; print_float(floatNumbers.(0));; print_string("\n");; print_char(letters.(4));; print_string("\n");; print_string(fruits.(1));;
set
method to reset the values of some elements of the array.RELATED TAGS
CONTRIBUTOR
View all Courses