listrangesml

SML Combing two functions (min, max) into one (range)


Anyway to combine these two functions which take a list and return the highest and lowest element. Want to output both at same time. Cheers

fun max[] = raise Empty 
    max[x] = x
    max(x::xs) =
  let 
    val y = max xs
  in
    if x > y then x else y
  end;

fun min[] = raise Empty 
  min[x] = x
  min(x::xs) =
     let 
       val y = min xs
     in
       if x < y then x else y
  end;

Solution

  • Here is a hint. Use the same basic logic. Write a function minmax to return a pair of values of the form (min,max) and then in the recursive step, use pattern-matching to extract the two values. A template would be:

    fun minmax [] = raise Empty
    |   minmax [x] = (x,x)
    |   minmax (x::xs) =
      let 
        val (a, b) = minmax xs
      in
        <fill in the code>
      end;
    

    In the above a will be the min and b the max. Given a and b and a third value x, return either (x,b) or (a,x) or (a,b), depending on how the inequalities play out. You will need more than one if.