Search code examples
functionfunctional-programmingsmlml

Standard ML: Return different types


I need to return a different value based on the function passed into another function.

So, given:

fun inc x = x + 1;

And:

fun double([]) = [] 
  | double(h::t) = 2 * h :: double(t);

You should be able to call the function I'm working on with either.

Example call (the function I'm making is named test):

test (inc, 5); - And it would return 6

-OR-

test (double, [1,2,3,4]); - And it would return [2,4,6,8]

I know that functions can't do this at face value, but is this possible through layers of abstraction?


Solution

  • Sure, that's possible:

    fun test (f, x) = f x
    

    testnow has the type (('a -> 'b) * 'a) -> 'b, which means that if you pass in a function that returns an int (like inc), the result will be an int and if you pass in a function that returns a list, the result will be a list.

    As a sidenote: double could be more easily/idiomatically be defined as fun double xs = map (fn x -> x*2) xs or val double = map (fn x -> x*2).