TopMenu

Printing and formatting outputs in F#

In this post we’ll discuss the very basic function that everyone uses in any language. When someone starts learning programming language very first thing they want to do is printing/writing out on console.

The Print

(image courtesy alinamelnikovaeportfolio.wordpress.com)

F# have two basic function “printf” and “printfn” to print out the information on console.

// The printf/printfn functions are similar to the

// Console.Write/WriteLine functions in C#.

e.g.

printfn "Hello %s" "World"
printfn "it's %d" 2016

The print function in F# are statically type checked equivalent to C-style printing. So any argument will be type checked with format specifiers. Below is list if F# format specifiers.

·         %s for strings

·         %b for bools

·         %i or %d for signed ints%u for unsigned ints

·         %f for floats

·         %A for pretty-printing tuples, records and union types, BigInteger and all complex types

·         %O for other objects, using ToString()

·         %x and %X for lowercase and uppercase hex

·         %o for octal

·         %f for floats standard format

·         %e or %E for exponential format

·         %g or %G for the more compact of f and e.

·         %M for decimals

Padded formatting

·         %0i pads with zeros

·         %+i shows a plus sign

·         % i shows a blank in place of a plus sign

Date Formatting

There’s not built-in format specifier for date type. There are two options to format dates:

1. With override of ToString() method

2. Using a custom callback with ‘%a’ specifier which allows a callback function that take TextWriter as argument.

With option 1

// function to format a date
let yymmdd1 (date:System.DateTime) = date.ToString("MM/dd/YYYY")
 
[<EntryPoint>]
let main argv = 
    printfn "using ToString = %s" (yymmdd1 System.DateTime.Now)
    System.Console.ReadKey() |> ignore // To hold the console window
    0 // return an integer exit code

With option 2

// function to format a date onto a TextWriter
let yymmdd2 (tw:System.IO.TextWriter) (date:DateTime) = tw.Write("{0:yy.MM.dd}", date)
 
printfn "using a callback = %a" yymmdd2 System.DateTime.Now

Ofcourse here option 1 is much easier but you can go with any of the option.

Note - Printing ‘%’ character would required to be escaped as it has special meaning.

printfn "unescaped: %" // error
printfn "escape: %%"

Read out more about F# print format specifiers here.

Getting started with writing F# code

In previous post we looked at the high level overview of Function programming language and introduction to F#. In this post we will start with basic things to learn Visual F#.

ToolVisual studio 2013

We’ll start with a console application. Launch the visual studio and Add a new F# console application.

Let’s name it “FSharp.Starters.Console”

Open the Program.fs file in editor and let’s write something in it. You’ll see an entry point method something like below:

// Learn more about F# at http://fsharp.net

// See the 'F# Tutorial' project for more help.

 

[<EntryPoint>]

let main argv =

    printfn "%A" argv

    0 // return an integer exit code

Let’ s change it to write something on console.

let SayHello() = printfn("Hello World!!")

 

[<EntryPoint>]

let main argv =

    SayHello()

    System.Console.ReadKey() |> ignore

    0 // return an integer exit code

So we have defined our very first function ‘SayHello()` which takes no argument and print simple “Hello World!!”. Now to run it simply press F5.



There are two ways you can run and test this F# code. Either via console application or using F# interactive windows. You can open the F# interactive windows in Visual studio from menu View -> OtherWindows -> F# Interactive.

Now you can go to Program.fs and select all code and press Alt + Enter to run the code in interactive window. If this doesn’t work then you can select all and right click in code editor and select “Execute in Interactive”

This will interpret the code in the interactive code and you’ll see the output like below:

val SayHello : unit -> unit

val main : argv:string [] -> int 

> 

Now the method ‘SayHello’ is ready to run. To invoke any method in Interactive we run it by typing method name and ending it with double semi colon e.g. “MethodName() ;;”. So let’s run the above code right away:

> SayHello();;

Hello World!!

val it : unit = ()

Congratulations! You now know how to run any Fsharp program/script. Let’s go ahead and put some arguments in the SayHello() method. To declare method argument is simple, just write the next to the method name like below:

let Greet To =

    if System.String.IsNullOrWhiteSpace(To) then

       "whoever you are"

    else

        To

 

let SayHello() To =

    printfn "Hi, %s" (Greet To)

Important Note: Next statement or method definition is identified by 4 spaces or single Tab in visual studio. Because there are not block defining like curly braces in C#. So it’s all defined via indentation.

E.g. Below statement would print “inside the if..” and return value “who ever you are”. The last statement in the same indentation is returned value.

    if System.String.IsNullOrWhiteSpace(To) then

       printfn("inside the if..")

       "whoever you are"

 

Take below example – The if statement would only print “inside the if..” the return value is out of if block.

    if System.String.IsNullOrWhiteSpace(To) then

       printfn("inside the if..")

    "whoever you are"

Now let’s run it interactive window. Select the these methods and right click in editor to choose “Execute in Interactive”.

val Greet : To:string -> string

val SayHello : unit -> To:string -> unit

val main : argv:string [] -> int

.. And with default or empty value:

> SayHello() "";;

Hi, whoever you are

val it : unit = ()

Hope you’re getting more confident, now let’s do something more like writing an algorithm to print nth Element of Fibonacci series. We’ll be using recursion to find the value. In F# the recursion is achieved via specifying a special keyword ‘rec’ with function. If you don’t specify the ‘rec’ word you’ll get the error while trying to achieve recursion.

let rec fib n =

    if n < 2 then

       n

    else

       fib (n - 1) + fib (n-2)

 

let find() n =

    printfn "%d" (fib n)

Now let’s run it:

val fib : n:int -> int

val find : unit -> n:int -> unit

> find() 10;;

55

What we learned in this post:

  1. Writing a basic function and running in console application.
  2. Running program in Interactive window.
  3. Using Managed library method in F# code.
  4. Using If..else.
  5. Methods with arguments.
  6. A basic recursion program.

To learn more about F# keywords, Symbols and literals follow below links:

Introduction to Functional Programming and FSharp for CSharp developers

As programmer/developers, you must know more than one type of programming language. I would say learning at least one Functional programming language will change your view to look at the problems. As we all C# based programmer knows that C# language is based on Object Oriented principle while the FSharp(F#) is based on completely different paradigm. In this blog post we’ll talk overview of functional programming, features, Introduction to F#, Success story and familiar terms of FSharp(F#) for C# developers.

Functional programming

where functions are first class citizens.

“In computer science, functional programming is a programming paradigm—a style of building the structure and elements of computer programs—that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data. It is a declarative programming paradigm, which means programming is done with expressions.” – Wikipedia

Here are some of least features a functional language must provide:

  • FirstClass functions
  • HigherOrderFunctions
  • LexicalClosures
  • PatternMatching
  • SingleAssignment
  • LazyEvaluation
  • GarbageCollection
  • TypeInference
  • TailCallOptimization
  • ListComprehensions

These features enable or support the following aims:

  • shorter programs (lower lines-to-effect ratio)
  • program correctness
  • expressive programs
  • Immutability

Simple Principle

As illustrated in figure above, the function takes and input and generates output. Every time you give input you can exactly one output, event after repeated over time. This is known as Idempotancy. The functional programming is more of dealing with Immutable.

The functional programming is being used in Academic and Industrial engineering since a long time. The “Erlang” is pure functional programming and became famous when robust and distributed systems were designed with the pure functional programming language. Developed and used by first Ericsson to build a fault –tolerant telecommunication systems, it’s not can be seen many famous applications systems like WhatsApp, RabbitMQ server, Facebook.

FSharp (F#)

Introduced in 2005 by Microsoft and supported by open source communities, F# consists of not only functional programming paradigm but also have flavor of paradigms of Imperative, Object, Asynchronous, Parallel programming including Metaprogramming so also known as Multi paradigm language. F# has a great part of open source community contribution which made it cross platform language for .Net Framework, Mono, Javascript.

Current stable release – 4.0 July, 2015.

Supported development tools

  • Visual studio
  • Mono Develop
  • Xamarin Studio
  • Sharp Develop
  • LINQPad

Official website - http://fsharp.org/

Enterprise level success story

Recently, I visited Jet.com development center (Hobokane, NJ) at their second technology meetup. Jet.com is a fastest growing popular ecommerce website to save more money to customers. The CTO Mike Hanrahan detailed out the high level of a progressive e-commerce system they built.



Mike shared their story of using F# as the backend language to build a smart “Reduced Price Calculation” engine to serve end customer with best savings. With combination of Event sourcing and immutable event buses they built a robust system using F# and other technologies. Readout the success story for more details about the solution at Microsoft site.

For C# Developers


Does this look familiar?

Well here’s couple of things I would like to mention about F# which would sound familiar:

  • Type inference (var in C#)
  • Method chaining, Aggregations (Linq in C#)
  • Access to the .NET Framework and any managed code assembly
  • Anonymous types
  • Type Extensions
  • Encapsulation
  • Lambda Expressions

F# allows you to create either a project or simply a script. So there could be libraries you can built or simply just write ‘.fs’ ‘.fsx’ script. Also you don’t have to run/debug the whole program every time. Visual studio provides a nice Interactive window to run F# code interactively. In next post we’ll start with writing our first program and understanding few basics. I’m pretty excited to start learning a new language as I mentioned in my Recap 2015 blog post. For now,

let Say() =

    printfn "Hello world to first F# function"

Interactive console -

> Say();;

Hello world to first F# function

val it : unit = ()

> 

Hope you enjoyed reading the introduction and if you’re excited then stay in touch by subscribing via email/rss to my blog or follow me on email for upcoming posts on learning FSharp.

More readings –

Customize reverse engineer code first EF6.x– EFPowerTool enhancement

Do you know you can customize the code generation for EF 6.x code first? If you are surprised then you can read out a start with guide here about the EF power tool to get more insights of code generation process.

What can I customize using EF power tools?

You can customize the class names, attributes, methods anything related to code that lies in your database context, entity or mapping classes.

Why would I need such customization?

Sometimes you may want to prefix/suffix the names of entities according to your requirement or may be putting some custom attributes etc.

What this blog is about?

This blog will not cover how to use the EF power tools. I already mentioned it in the start of the post about the tutorial where you can learn about it.
In this blog we’ll talk about some enhancements which would make the tool a bit more flexible for generating classes with directory hierarchy based on namespace. Well this sentence went bit too long. So I’ll start step by step understanding the issue and what could be the proposed fix:

I have encountered couple of questions in forums that the EF code templates are only generating code in a particular designated directory. Below are the files which you would get after installing the EFPowerTool.

Now, if you have already existing Code first in the project and you want to use the EF code template to customize them. You’ll end up having below directory hierarchy after code generation. Well you have to change the namespaces and directory hierarchy according to your existing structure of code first classes.

After doing a bit of research in the EF6.x source code, Found that the Model and Mapping directories including the namespaces are hardcoded in the code. To fix this problem I had to understand the whole process of code generation. So after few hours of research I figured out that the Custom code template files have access the EfTextTemplateHost object via Host property.

Also I found below properties in the EfTextTemplateHost object which can be used to change the namespace for code generation.

        public string Namespace { get; set; }

        public string ModelsNamespace { get; set; }

        public string MappingNamespace { get; set; }

So this properties can be utilized to change the existing generation behavior for placing the classes in hierarchy w.r.t namespaces. So I added a new utility class which can sync the namespace with directory hierarchy. (sourcecode here). It might not be covering all the cases because I wrote some tests to ensure existing functionality is not broken. And to verify if the new required changes are working. Below are the files which were affected for this change:

src/PowerTools/CodeTemplates/ReverseEngineerCodeFirst/Context.tt

src/PowerTools/CodeTemplates/ReverseEngineerCodeFirst/Entity.tt

src/PowerTools/CodeTemplates/ReverseEngineerCodeFirst/Mapping.tt

src/PowerTools/Handlers/ReverseEngineerCodeFirstHandler.cs

src/PowerTools/Utilities/ProjectFilesPathGenUtility.cs

The all .tt code template files have sample added in the comments how you can define the namespace to get the structure generated in desired hierarchy.

                /*

                                   Customize the file generations according to namespace hierarchy

                                   efHost.Namespace = "DataAccess";

                                   efHost.ModelsNamespace = "DataAccess.Models";

                                   efHost.MappingNamespace = "DataAccess.Mappings";

                */

This settings will generated below directory hierarchy.

Well this would solve problem of few askers like here and here. I have submitted a PR to EF team for EF6.x repository. While waiting for feedback I have created an experimental branch of EFPowerTool on github. You can download and install the extension installation file from here (Right click and choose save as…). Those who are interested in making more enhancement of want to review this changes feel free to review/test. Raise any issues on github I’ll try to work on it with you.

Hope we can make the beta release to bits of RC for the extension.