Antonis
Antonis

Reputation: 35

find max/ min in int array structure in ml

Im new in ML and I am having quite a hard time trying to extract the min or max of an array of integers.
I have created the array from a list of integers using Array.fromList.

A hint could be very useful since functions like hd, or tl do not work on arrays

Upvotes: 1

Views: 2453

Answers (2)

Jesper.Reenberg
Jesper.Reenberg

Reputation: 5944

As stated you have basically the same functionality in SML.
When working on arrays instead of lists, you have to use functions that takes an array as input, and not a list. Kind of goes without saying.

Basically you can solve the problem the same way you would, if it was a regular list. However you just need to use the folding functionality from the Array module. Unlike regular lists, we can't pattern match them to decompose it into the first element and the rest of the list, so we must select the first element through the sub function. To make sure that there are elements in the list, you can wrap it with a test that compares the length of the array.

fun min_arr arr = Array.foldl Int.min (Array.sub (arr, 0)) arr


- val a = Array.fromList [5,76,2,6,8,2,3,7,81,3];
val a = [|5,76,2,6,8,2,3,7,81,3|] : int array
- min_arr a;
val it = 2 : int

To find the biggest element in the list, you could exchange the Int.min function with Int.max.

Upvotes: 4

gasche
gasche

Reputation: 31459

In OCaml:

let min_array arr = Array.fold_left min arr.(0) arr

This code uses arr.(0) as an initial candidate for minimum value, and fails if the array is empty, so you may want to check for that or use a domain-specific initial candidate that is always bigger than the real minimum (I'm personally wary of using max_int in these situations).

I see that SML has a foldl function that allows to do the same thing. I'll let you adapt the syntax as needed.

Upvotes: 3

Related Questions