Nor­mally, 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 within Win­dows Explorer you can exe­cute it directly 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 Visual Stu­dio, whilst writ­ing F# as a script you have access to a num­ber of com­piler direc­tives such as __SOURCE_DIRECTORY__ and __SOURCE_FILE__ which returns the cur­rent direc­tory and file­name respectively.

As a sim­ple exam­ple, here’s a script I put together in 5 min­utes that iden­ti­fies image files in the cur­rent direc­tory and sub-directories 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 output:

image

Part­ing thoughts…

Using F# in this fash­ion has the obvi­ous ben­e­fit that you don’t have to learn another lan­guage just so that you can hack some scripts together 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#.

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

Share

Leave a Reply