Search code examples
functional-programmingsmlcurryingpartial-application

Creating a function that returns a curried function (SML)


I've written a function that calculates a value of x, of a polynomial made from a list of reals.

infixr 5 ^^;

fun (x:real) ^^ 0 = 1.0
  | (x:real) ^^ n = x*(x^^(n-1));

fun poly [] (x:real) = 0.0
  | poly (hd::tl) (x:real) = hd*(x^^(length tl)) + poly tl x;

This code all works perfectly fine, and I'm quite proud of it.

I have managed to create polynomial functions using partial application:

> fun f x = poly [3.0,2.0,1.0] x;
val f = fn : real -> real

> f 2.0;
val it = 17.0 : real

Creating the mathetmatical function:f(x) = 3*x^2 + 2*x + 1

This is all fine, but I want to be able to construct a function by this method:

fun f x = polyGen [1.0,2.0,3.0];

And it will give me an equivalent function to the one above. Is this possible? I know it seems trivial, I could just put an x there as I did before and get on with my life. But I'm just curious on how someone would get around this problem!

Thanks in advance, Ciaran

EDIT:

fun polyGen L = let fun poly [] x = 0.0
                      | poly (hd::tl) x = hd + x*(poly tl x);
                in fn x => poly L x end;

Lovely!


Solution

  • If I understand your question correctly, then you don't need to define anything else at all. With the function poly that you have you can already do

    val f = poly [3.0, 2.0, 1.0]
    

    which defines f as a function of type real -> real.