PDA

View Full Version : standard ML functional programming, Finding the maximum


edeita2
04-11-2004, 08:22 PM
I`m also trying to write a function which is able to find and return the maximum element in a list of positive integers.Here`s my code:

- fun max nil = 0 |
= max(h::t) = if (h > t) then h else t;


since ML doesn`t have those loops like java or C++, I don`t know how I`m going to compare the elements to each other of the rest(tail = t, head = h)
I`m grateful for your suggestions..

GnuVince
04-11-2004, 11:12 PM
I don't know SML, but here's how it would be done in O'Caml (very close relative)


let max lst =
let rec max_aux max_value lst = match lst with
[] -> max_value
| hd::tl ->
if hd > max_value then max_aux hd tl
else max_aux max_value tl
in
max_aux 0 lst;;


You basically have a function inside a function with a function argument that holds the currently largest value. Hope you can translate this.

jemfinch
04-12-2004, 12:12 PM
What if the list is composed entirely of negative numbers?


fun max [] = NONE
| max (hd::tl) = let
fun aux soFar [] = SOME soFar
| aux soFar (hd::tl) =
if soFar > hd then max soFar tl else max hd tl
in
aux hd tl
end


So you'll return NONE if it's an empty list, and SOME x where x is the greatest element in the list if the list isn't empty.

Jeremy

edeita2
04-12-2004, 10:22 PM
Thanks GnuVince & jemfinch for your ideas, they were useful, now I`m done with that problem...