Currying and F#

Posted: August 15, 2009 in F#

I have just started taking a look into the F# programming language for the past few days.While going through the functions in F# I found something very interesting.Let’s consider a very simple function which multiplies two integers.

let mul x y = x * y;;

Now if I call mul 5 10 I get the output 50 as expected.This is fine so far.But what happens if I do not pass the second argument and make a call like mul 5.Going by knowledge of C# it should throw an error but actually it does not.It returns me something like as shown below.

> mul 5;;
val it : (int -> int) = <fun:it@18-1>

Now what is this “val it : (int -> int) = <fun:it@18-1>”?? This basically a function which accepts an integer and returns an integer.So mul 5 returns me an anonymous function.So I assigned this anonymous function to variable as shown below:

> let x = mul 5;;

And x 10 returns 50. So basically the call mul 5 returns an anonymous function which is equivalent to

let mulFive y = y *5

So in F# every function can be broken down to a set of function which accepts an argument and returns another anonymous function.This is what is the basic essence behind Currying, a feature which was there in functional languages like Haskell and ML for quite long time.

  1. ghills says:

    I am not familiar with F# but the idea of currying is something more familiar from using LISP. Higher order functions can make for some really interesting implementations.

  2. Sankarsan da..So again back in action..always wait for your post..:)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s