Basic input/output syntax

We are now going to see how to write and read in F#. To read and write into the console, we can use the following commands:

  • To write: System.Console.Write("Welcome!")
  • To read: System.Console.Read()
  • To print: printfn "Hello"

Let's compare F# with C#:

                                F#

C#

The F# user is free from the obligation of defining types; for example: let square x = x* x

The compiler can identify (integer * integer) or (float * float) when we pass a value.

 

The C# user is bound to provide a type:

Public int square(int x){ return x = x*x ; }

 

F# has immutable data, and the value never changes; for example: let number = [3;2;1]

let moreNumber = 4:: number

In the preceding example, to add one more number, (4), we need to create a new list of items using number, and add the new record, 4 in this case. The same list doesn't get modified for safer asynchronous execution and a simplified understanding of a function.

C# has mutable as well as immutable data. Strings are immutable, the rest are all mutable, for example:

var number = new List<int> {1,2,3}; number.Add(4);

In the preceding example, we created a list and added a new item to the same list. The list gets modified.



F# compiles code in an order. It is favoured for data processing and algorithmic computation. It doesn't work on visibility; it works sequentially.

 

C# code works on visibility. The sequence doesn't matter.

The order of files in a project matters in the F# solution. A file used in any method should be placed above the file where the method has been used.

 





The order doesn't matter in C#.

 

 

 

 

F# has precise syntax; it focuses on what not and how; for example:

let square x = x*x

let squared = List.map square[1;2;3]  // using square function

Right-click execute | result 1;4;9

F# uses declarative syntax, not imperative syntax as in C#. F# helps us to minimize accidental complexity, meaning complexity that is not a part of the problem, but which we introduced as part of the solution, for example:

let rec quicksort = function | [] -> [] | x :: xs ->  let smaller = List.filter((>)x) xs let larger = List.filter ((<=)x) xs

Quicksort smaller @ [x] @ quicksort larger:

 

Let sorted = quicksort [4;5;4;7;9;1;6;1;0;-99;10000;3;2]

 

rec is used for a recursive function. It is assigned in the sorted result. Run it and you will get a sorted result. It is a very simple sorting function with less complexity than C#, which has a high chance of errors.

 

C# code implementation is more about how to implement. It sometimes increases unnecessary complexity as part of the solution to a problem.

Quick sort has a very complex algorithm and a high chance of increasing accidental complexity.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.168.172