Page 1 of 1

F# - An Introduction to Currying

#1 Sergio Tapia  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1251
  • View blog
  • Posts: 4,168
  • Joined: 27-January 10

Posted 08 November 2010 - 07:45 AM

Currying in functional programming is taking a function that receives more than one variable and acting on it as if it were a chain of methods each with a single argument.

For example, when you do this:

let AddThis a b = a + b


You're actually creating two different methods. One that uses 'a' and one that uses 'b'. When you have a function that has more than one parameter, F# treats that function as a chain of functions, currying each function as you go along to get the result that you need.

Here's an example of currying that add's two numbers together.

#light
open System

let addTwoNumbers x y = x + y
let addTenToNumber = addTwoNumbers 10

Console.WriteLine(addTenToNumber 6)



Here's the output:

> 
16

val addTwoNumbers : int -> int -> int
val addTenToNumber : (int -> int)



Every function in F# has one argument and returns on Value. You can have it return a 'Unit' which is similar to the void keyword in other languages.

The code above is actually two distinct functions. One takes our argument 'x' and creates a new anonymous function that will add the value of 'x' to the value of that functions argument.

The new function takes the 'y' argument and returns the result.


Now let's trying currying with strings.

let formatMessageComplete firstName lastName = firstName + " " + lastName + ", thanks for coming in."
let formatMessage = formatMessageComplete "Sergio"

Console.WriteLine(formatMessage "Tapia")



Ouput:

> 
Sergio Tapia, thanks for coming in.

val formatMessageComplete : string -> string -> string
val formatMessage : (string -> string)




Remember: You can select code inside Visual Studio 2010, and press Alt+Enter to run the code.

Is This A Good Question/Topic? 1
  • +

Replies To: F# - An Introduction to Currying

#2 Shane Hudson  Icon User is offline

  • D.I.C Technophile
  • member icon

Reputation: 342
  • View blog
  • Posts: 1,286
  • Joined: 06-December 09

Posted 08 November 2010 - 02:32 PM

Not a language I am planning on delving into any time soon but very well written tutorial! I had very heard of this concept before, fascinating how different it is to what I usually use (OOP, mainly C# and Java).
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1