Use F# to meet your scripting needs

Nor­mal­ly, with lan­guages like C# or Java, there is quite a bit of over­head in cre­at­ing a quick and dirty pro­gram to do small tasks like bulk renam­ing files in a direc­tor, etc. This is the spot that is filled by script­ing lan­guages like Python, Perl and Ruby, but did you know that you can write F# code in a script­ing style too?

If you have F# installed, it will reg­is­ter the .fsx exten­sion as F# script files. From with­in Win­dows Explor­er you can exe­cute it direct­ly by select­ing the “Run with F# Inter­ac­tive” con­text menu option:

image

Exe­cut­ing a F# script file this way would send the file to the con­sole ver­sion of F# inter­ac­tive, fsi.exe.

You can also dou­ble click on the file to edit it inside Visu­al Stu­dio, whilst writ­ing F# as a script you have access to a num­ber of com­pil­er direc­tives such as __SOURCE_DIRECTORY__ and __SOURCE_FILE__ which returns the cur­rent direc­to­ry and file­name respec­tive­ly.

As a sim­ple exam­ple, here’s a script I put togeth­er in 5 min­utes that iden­ti­fies image files in the cur­rent direc­to­ry and sub-direc­to­ries and renames them to be title cased, e.g. “my_image.jpg” will become “My_Image.jpg”.

Exe­cut­ing this script gives the fol­low­ing out­put:

image

Parting thoughts…

Using F# in this fash­ion has the obvi­ous ben­e­fit that you don’t have to learn anoth­er lan­guage just so that you can hack some scripts togeth­er to per­form sim­ple tasks for you. Build automa­tion tools is one area this can be very use­ful. Inspired by the Rake build tool of the Ruby world – which allows you to write your build script in Ruby – we now have a Fake build tool that lets us do the same with F#.

Anoth­er ben­e­fit of using F# as a script­ing lan­guage is per­for­mance. Script­ing lan­guages typ­i­cal­ly sac­ri­fices exe­cu­tion speed for the ease of mod­i­fy­ing and deploy­ing. F# on the oth­er hand, is not inter­pret­ed and is always com­piled first so it can be faster than pure script­ing lan­guages.