Check for a sequence index using valid_index() in Euphoria

Overview

The Euphoria language provides one with so many handy methods which carry out really important functions in our programs. In this shot, we’ll look at the valid_index() method.

The valid_index() method

The valid_index method is a built-in method in Euphoria used to check if an index is valid. It checks if an index can be found in a sequence variable. When the valid_indexd() method checks in a sequence to see if a provided index value makes sense (that is can be found in the sequence), it returns integer value 1 if true, and if false, it returns 0.

Syntax

 valid_index(search_sequence, index)

Parameters

  • search_sequence: This is the sequence which will be checked to ascertain if a particular index is found in it.
  • index: This is the index whose validity is being checked for.

Return value

This function returns an integer value of 1 if the index is valid and 0 if it is not.

Example

--include the required module in the code
include std/sequence.e
sequence search_sequence = "This is the search sequence"
--valid index instance
atom output1 = valid_index(search_sequence,3)
--invalid index instance
atom output2 = valid_index(search_sequence,70)
--this if block show example of a valid index
if (output1 = 1 ) then
printf(1,"it is a valid index, output1 is : %d\n",output1)
else
printf(1,"\n it is not valid : %d", output1)
end if
--while this if block here show example of an invalid index
if(output2 = 0) then
printf(1,"it is not a valid index, output2 is : %d",output2)
end if

Explanation

  • Line 2 : We include the required module in the code snippet.
  • Line 4: We declare the search_sequence variable.
  • Line 7–9: We use the valid_index() method and save the outcomes in output1 and output2 respectively.
  • Lines 13–18: We use an if block to show the example of a valid index.
  • Lines 21–23: We use another if block to show the example of an invalid index.

Free Resources