display | more...

A feature of certain functional programming languages such as ML. In languages such as C, pascal, Java etc. if you have a function of several arguments then you have to supply all of the arguments at once. In ML however i can do the following

fun map (f:'a->'b) (x::l) = (f x) :: (map f l)
|map _ [] =[];

This function takes a list of elements of type 'a and a function that takes an argument of type 'a and returns a value of type 'b, as arguments and returns the list obtained by applying f to all the elements of the list. The ML type of this function is fn : ('a -> 'b) -> 'a list -> 'b list.

An equivalent function could easily be written in C, using function pointers, although the list would have to be of type void * in order to mimic the polymorphism we have in ML.

But what you can do in ML that you can't do in traditional languages is something like this :

val Mymap = map f;
where f is a function already defined. We have applied the function map partially to f. Mymap is a new function that takes a list as a parameter and applies f to all the elements of the list. Mymap is not just an alias or a macro for map f : if you change map or f, Mymap will not be changed. You can even do something like
val mymap2= map (map f)
which is a function that takes a list of lists of items type 'a and returns a list of lists of items obtained by applying f.

A more down to earth example is as follows:

fun derivative f (delta:real) x = ((f (x+delta))-(f (x-delta)))/(2.0*delta);
As you can see, this function calculates the derivative of f at the point x by calculating the slope between x-delta and x+delta. Still nothing I can't do in C. But in ML I can do this :
val derivativeOfF = derivative f .001;
like before derivativeOfF is a new function that is an approximation of the derivative of f

In the end, it's a pretty cool feature that like many of the elements of languages like ML helps you to write concise and elegant code.

Log in or register to write something here or to contact authors.