Syntactical similarities and differences
Let's expand upon the preceding example and compare the syntactical differences between F# and C# through another simple example, the sum of a square
method. A shorter and elegant looking functional syntax follows:
let square x = x * x let sumOfSquares n = [1..n] |> List.map square |> List.sum
Here you see the use of one of F#'s celebrated operators, that is, the |>
pipe forward operator. It essentially performs piping operations by passing the results from left the side of the function to the right side, and can be concatenated.
Running this program in F# the interactive console yields the following results for
sumOfSquares 2
and
sumOfSquares 3
respectively:
The sum of the squares method in C# looks something ...
Get Learning F# Functional Data Structures and Algorithms now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.