Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » F# » F# Types and the Forward Pipe Operator |>

F# Types and the Forward Pipe Operator |>

Looking at F# Types (Especially Functions) and the Forward-Pipe Operator.

Author Rank:
Total page views :  5552
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor


Typing the command into F# interactive (from the left column) we can see the value of our expression and investigate some of the different types we'll be running into. 

Note: In case you don't have the F# environment, in my previous post I talked about how to get everything set up.

Command

Response

Type

3;;

val it : int = 3

int - Int32

3u;;

val it : uint32 = 3u

Unsigned int - Uint32

3L;;

val it : int64 = 3L

Long - Int64

3UL;;

val it : uint64 = 3UL

Unsigned Long - UInt64

3s;;

val it : int16 = 3s

short - Int16

3us;;

val it : uint16 = 3us

Unsigned short - UInt16

3.0;;

val it : float = 3.0

Float - floating point

"Hello World";;

val it : string = "Hello World"

String

'c';;

val it : char = 'c'

Character

These are pretty simple… Let's look at something that will seem a bit new to C# imperative programmers:

Command

Response

(+);;

val it : (int -> int -> int) = <fun:it@42>

As you can see, the "(+)" actually has a value in F#.  The value of "(+)" in F# takes our int operator and turns it into a prefix function that accepts two integers (the first two ints in "int -> int -> int") and has a return value of an integer ("int -> int -> int").  Another way to look at it is:

In F# (and all functional programming languages) the function is a first class value, just like numbers and characters.  This takes a bit of getting used to but is really the power and beauty behind the language.

If we want, we can define our own functions using the function syntax (above).  The keyword for creating our own function is "fun".  Let's define a function that returns the same value we passed in.

Command

Response

fun x -> x;;

val it : 'a -> 'a = <fun:clo@0_1>

Now we have declared a new function that takes and 'a ('a->'a) and returns an 'a ('a->'a) .  What's it mean?

F# tries to be as generic as possible by default.  'a is a generic "type" so anytime you see something like 'a, think to yourself "something that is an a" or "something of type a".  If you are familiar with C# this would have the same idea as the following generic function except in the generic function we use 'T' instead of 'a:

public T DoSomething<T>(T value)
{
     return value;
}

So what happens if we constrain the output a bit?  We know "(+)" is an "int -> int -> int" so what if we supply one of the parameters?  What would "(x + 1)" be?

Command

Response

fun x -> x + 1;;

val it : int -> int = <fun:clo@0_2>

You can see, we now have a function that will take an int as the input parameter ("int -> int") and will receive and int as the result of the operation ("int -> int").

The thing to notice is that the interpreter will interpret the variable types and do this as generically as possible which makes for much greater code reuse.  This also forces to think generically and will help make us better C# programmers.

Here is another example using a string.

Command

Response

fun x -> x + " World";;

val it : string -> string = <fun:clo@0_3>

We don't have to specify the type but it is in there.

In the interpreter, we can apply functions and immediately see the results.  For example, if we type "3+3;;" we get the following:

> 3+3;;
val it : int = 6 

Really, the "+" by itself is just an operator (and not really a function).  We have to surround the "+" with parenthesis "(+)" to turn it into a function.

To demonstrate, if we enter "+;;" as a command by itself we receive an error:

>  +;;
 
  +;;
  --^^^
 
stdin(63,2): error: syntax error.

But if we wrap it in parenthesis like "(+)", we now have a function.

> (+);;
val it : (int -> int -> int) = <fun:it@65> 

This function expects two integers and returns an integer so we pass the first two parameters into the function in the following way:

> (+) 3 3;;
val it : int = 6

We can do the same thing with strings because the operator is overloaded for string concatenation and the interpreter can figure out the necessary overload operator to use:

> (+) "Hello " "World";;
val it : string = "Hello World" 

We can declare our own function and have it behave the same way:

> (fun x y -> x + y) 3 4;;
val it : int = 7

The first value "3" is applied to the first parameter of our method (x) , and the second value gets applied to the second parameter of our method (y), then the function is executed and we see the result as 7.

The same thing works with string concatenation:

> (fun x y -> x + y) "Hello " "World";;
val it : string = "Hello World"

Partial application. 

What if we provide only one of the two parameters required by our function?

> (fun x y -> x + y) 3;;
val it : (int -> int) = <fun:it@79>

We now have defined a new function of type "int -> int" which is kind of like the function (fun y -> y + 3).  This function is only partially applied.  So we can now use this partially applied function and apply the last input.

((fun x y -> x + y) 3) 4;;
val it : int = 7

So what's happening?  First, our function is interpreted as "int -> int -> int"

Next, the value "3" is applied to the first member of our function "int -> int -> int" and we are left with the last two "int -> int -> int"

Our new function "int -> int" will add 3 to any value that is applied to it so when we apply "4" to the next position the function can be evaluated to an integer.

This may seem pretty basic, but here's point.  With functional programming we often have to think of functions not in terms of something that is applied to two values, but as a transformation of our inputs which are applied to our function.  You'll see more once we get into lists in an upcoming article. 

Here's an example of what I'm talking about... What if we want a way to apply a value from the left hand side of our equation instead of the having the input on the right?   To do this we have a special F# forward-pipe operator "|>" which we can think of as the push operator because it "pushes" the value from the left hand side of the function to the first parameter of the function.

So now we have a bunch of different ways to express the same thing

> 4 |> (fun x y -> x + y) 3;;
val it : int = 7

The precedence is pretty important here. Just like in most programming languages, everything in parenthesis are evaluated first (our function).  In this code, the right hand side of the "|>" operator is evaluated before the left.  (If there are a series of "|>" operators they are applied left to right after their contents have been evaluated, "pushing" the data from left to right.)

So after our function is intrepreted, we apply 3 to the first input

And are left with (int->int).  Then we apply 4 to the beginning of (int->int) to get the result (7).

Take a look at the following declaration and see if you can figure out what's happening in the following three commands (remember, anything in parenthesis is executed first):

> 4 |> ( 3 |> fun x y -> x + y);;
val it : int = 7

> "World" |> (fun x y -> x + y) "Hello ";;
val it : string = "Hello World"

> ("World" |> (fun x y -> x + y)) "Hello ";;
val it : string = "WorldHello "

See if you can follow what's happening in the following statement:

> "World" |> ("Hello " |> (fun x y z -> x + y + z)) "There ";;
val it : string = "Hello There World"

Anyways… the forward-pipe operator ("|>") will be one of your best friends in F# so it is important to understand how it works.

Let's look at the definition of our push operator in a bit more detail by looking at the definition just like we did with the addition operator earlier "(+)":

> (|>);;
val it : ('a -> ('a -> 'b) -> 'b) = <fun:it@100>

This is confusing at first, but will make sense the more you see it.  Let's break it down...

We have a function that takes something of type a in as a first parameter:
('a -> ('a -> 'b) -> 'b)

As a second parameter, our function takes in another function!  This second parameter function takes something of type a (again) and outputs something of type b:
('a -> ('a -> 'b) -> 'b)

The final output is our thing of type b:
('a -> ('a -> 'b) -> 'b)

Let's take a look at how the compiler can figure the types out...

If we have our function:

> fun x y -> x + y;;
val it : int -> int -> int = <fun:clo@0_5>

And push "4" in

4 |> fun x y -> x + y;;
val it : (int -> int) = <fun:it@103>

We are saying 4 is our first member so we know 'a is an int

4 |> fun x y -> x + y;;

('a -> ('a -> 'b) -> 'b)

So we end up with a signature where 'a has been constrained to an int

(int -> (int -> 'b) -> 'b)

This is one of the nice things about using the forward pipe.  Because F# is generic, it sometimes needs help figuring out what types should be applied to the generic functions and using the pipe operator makes this explicit earlier in the statement.  This means we don't have to be as explicit with our types which will make coding much easier. 

We know that our function is using integers and now has to be (int -> int -> int)

> fun x y -> x + y;;
val it : int -> int -> int = <fun:clo@0_6>

so our addition function is applied to the second parameter of our forward pipe

4 |> fun x y -> x + y;;

(int -> (int -> 'b) -> 'b)

So what's 'b?

We know our addition function after applying the integer "4" is of type

(int -> int -> int)

Which is getting applied to our second function parameter

(int -> 'b)

(int -> int->int)

So 'b has to be a function that takes an int and returns an int "(int -> int)" which is true because after our partial application we have function that adds 4 to anything we pass in.

This default generic way of thinking and applying functions to other functions is one of the challenging things to understand when making the move from imperative C# to functional F# programming so take your time and try to make as much sense of this as you can.  Thinking generically in this way will often help you see a bigger picture whether you are working with imperative or functional code.

Let's look at a sample from a C# perspective that may clear things up, let's say we have a generic extension method:

public static class Extenstions
{
    // similar to but not quite the same as ('a -> ('a -> 'b) -> 'b)
    public static V InvertOrder<T, U, V>(this T tVal, Func<T, U, V> f, U uVal)
    {
        return f(tVal, uVal);
    }
}

C# extension methods allow us to do a (somewhat) similar thing as in the F# pipe and invert the order but we end up with lots of  messy code lying around so it is not as practical as when using F#.

(4).InvertOrder((x, y) => x + y, 3)

I've found F# to be extremely fun to program with because of the flexibility and expresiveness of the language.  As you can see, there are tons of ways of saying the same thing.

Next time we'll look at the power of the forward-pipe "push" operator and how we can use it to process groups of items.

Until next time,
Happy coding 


Login to add your contents and source code to this article
 About the author
 
Matthew Cochran
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.