Learning F#, Post 1: Forward Pipe
What is F#?
F# is a new functional programming language that is being developed here at Microsoft. Don Syme invented the language. Currently, the Managed Languages team is taking Don's work and turning F# into one of our production languages, alongside C#, Visual Basic, IronRuby, and IronPython. Since I find the project interesting, I've undertaken to learn F#. Don Syme invented the language. Currently, the Managed Languages team is taking Don's work and turning F# into one of our production languages, alongside C#, Visual Basic, IronRuby, and IronPython. Since I find the project interesting, I've undertaken to learn F#.
I'm learning F#
My Comparative Languages class back at Virginia Tech was one of my all-time favorites, but it involved only a meager treatment of functional programming. I wrote a little Scheme, but that was it. To learn F#, I expect my biggest task is simply to understand functional programming in general: to understand how it differs from imperative and object-oriented programming. To this end, I chose a language feature of F# to investigate: the forward pipe. Also, I chose an arbitrary task to code up, to flex my limited F# knowledge.
What is the Forward Pipe?
In F#, simple function calls in F# look like this:
String.split [' '] text
In this case, String.split is the function, and [''] and text are the parameters. The parameters come after the function name. The Forward Pipe operator ( |> ) changes this order.With the Forward Pipe, a parameter preceding the function name is "piped" to the function, like this:
text |> String.split['']
It's important to note that the piped parameter is the last parameter in order (so text is ordered after [''] in this example).
More examples of the forward pipe can be seen in this code:
#light
//you may have to change this reference path:
#I @"D:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\v3.0\"
#r @"WindowsBase.dll"
#r @"PresentationCore.dll"
#r @"PresentationFramework.dll"
//opening namespaces
open System
open System.Windows
open System.Windows.Controls
//simple object manipulation
let win = new Window()
win.Title <- "Keats"
win.Show()
//function definition
let labFromText text =
let newLab = new Label()
newLab.Content <- text
newLab
//function definition
let surroundWithPanel objs =
let pan = new StackPanel()
List.iter ( fun x -> pan.Children.Add( x ) |> ignore ) objs
pan
//lots of forward pipes here:
win.Content <- "When I have fears that I may cease to be"
|> String.split [' ']
|> List.map labFromText
|> surroundWithPanel
//this code allows the app to be compiled and run:
#if COMPILED
[<STAThread()>]
do
let app = new Application() in
app.Run() |> ignore
#endif