Logo

Programming-Idioms

History of Idiom 20 > diff from v56 to v57

Edit summary for version 57 by andrepd:
[Caml] typo in comments

Version 56

2019-09-26, 17:04:14

Version 57

2019-09-26, 17:04:41

Idiom #20 Return two values

Implement a function search which looks for item x in a 2D matrix m.
Return indices i, j of the matching cell.
Think of the most idiomatic way in the language to return the two values at the same time.

Idiom #20 Return two values

Implement a function search which looks for item x in a 2D matrix m.
Return indices i, j of the matching cell.
Think of the most idiomatic way in the language to return the two values at the same time.

Code
module Arr = Bigarray.Array2

let search array value =
	let x_max = Arr.dim1 array in
	let y_max = Arr.dim2 array in
	let rec loop x y = 
		(* End of array *)
		if x = x_max then
			raise Not_found
		(* End of row, go to next *)
		else if y = y_max then
			loop (x+1) 0
		else 
			(* If found, return it *)
			if array.{x,y} = value then
				(x,y)
			(* Otherwise go to next row *)
			else
				loop x (y+1)
	in
	loop 0 0





		
Code
module Arr = Bigarray.Array2

let search array value =
	let x_max = Arr.dim1 array in
	let y_max = Arr.dim2 array in
	let rec loop x y = 
		(* End of array *)
		if x = x_max then
			raise Not_found
		(* End of row, go to next *)
		else if y = y_max then
			loop (x+1) 0
		else 
			(* If found, return it *)
			if array.{x,y} = value then
				(x,y)
			(* Otherwise go to next col *)
			else
				loop x (y+1)
	in
	loop 0 0