Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ocaml

How to reset value of an element of array with Array.set in Ocaml

okwudili onyejiaku

Overview

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.

Syntax

Array.set arr n new_value
Array.set syntax

Parameters

  • 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.

Return value

The value returned is the element with a new value.

Example

(*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));;
Reset array elements with Array.set in Ocaml

Example

  • Lines 2–5: We create some arrays.
  • Lines 8–11: We use the set method to reset the values of some elements of the array.
  • Lines 14–20: We access the elements for which we reset the values and print them to the console.

RELATED TAGS

ocaml
RELATED COURSES

View all Courses

Keep Exploring