Snippets created by Tomas Petricek

  • Filtering lists

    Two functions showing how to filter functional lists using the specified predicate. First version uses naive recursion and the second one is tail-recursive using the accumulator parameter.

    65 people like this

    Posted: 6 years ago by Tomas Petricek

  • Random walk

    Create sequence of floating point values generated by random walk process. Functional solution using sequence expressions and yield! construct in a tail-call position.

    38 people like this

    Posted: 6 years ago by Tomas Petricek

  • Hello world (F#)

    Classical "Hello world" example that prints a message to the console output. This version uses F# printfn function to do the printing.

    176 people like this

    Posted: 6 years ago by Tomas Petricek

  • Friendly date formatting

    Generates a friendly string describing a date relatively to the current date and time. The function returns strings like "2 secs ago", "yesterday" or "3 years ago".

    38 people like this

    Posted: 6 years ago by Tomas Petricek

  • Nice formatting of type names

    Add extension to System.Type that returns the name of type including generic arguments in a nice readable format. It returns only short names of generic type and type arguments.

    20 people like this

    Posted: 6 years ago by Tomas Petricek

  • Compiling quotations

    Demonstrates how to compose code at run time using F# quotations (both typed and untyped) and how to compile and run the quotation using F# PowerPack API.

    56 people like this

    Posted: 6 years ago by Tomas Petricek

  • Creating objects with events

    This snippet shows how to create objects with events in F#. It shows both simple event (to be used from F#) and a .NET compatible event with specific delegate type.

    77 people like this

    Posted: 6 years ago by Tomas Petricek

  • Traverse quotation

    Shows how to use the 'ExprShape' module to recursively traverse an entire quotation and how to write quotation transformations. As an example, the snippet replaces all numeric constants in the quotation and then runs the transformed code.

    25 people like this

    Posted: 6 years ago by Tomas Petricek

  • Take every Nth element of sequence

    A function that takes every Nth element of a sequence where N is passed as an argument. The snippet shows a naive function and a function using IEnumerator directly to provide an efficient implementation.

    30 people like this

    Posted: 6 years ago by Tomas Petricek

  • Find verbose .NET types using Reflection

    Searches all (currently loaded) types using Reflection to find the types with longest and shortest names of members. Uses average length of all type member names as a metric.

    13 people like this

    Posted: 6 years ago by Tomas Petricek

  • Dynamic operator using Dynamic Language Runtime

    The snippet shows a simple implementation of the dynamic operator (?) that uses Dynamic Language Runtime and the C# implementation of dynamic operations. The snippet shows how to invoke instance methods with single argument.

    32 people like this

    Posted: 6 years ago by Tomas Petricek

  • Enumerator computation builder

    The snippet defines computation builder for working with IEnumerator. The bind operation (let!) reads next element from the enumerator, so the computation can be used for expressing things that cannot be written just using seq.

    29 people like this

    Posted: 6 years ago by Tomas Petricek

  • Doughnut chart using chart controls

    The snippet shows how to use Microsoft Chart Controls (available in .NET 4.0 and for .NET 3.5) to draw a Doughnut chart. The sample shows proportion of seats taken by parties in UK elections.

    84 people like this

    Posted: 6 years ago by Tomas Petricek

  • Candlestick chart using chart controls

    The snippet shows how to use Microsoft Chart Controls (available in .NET 4.0 and for .NET 3.5) to draw a Candlestick chart visualizing stock prices. The sample uses price of MSFT stocks over 20 days.

    17 people like this

    Posted: 6 years ago by Tomas Petricek

  • Simple asynchronous functions

    The snippet demonstrates how to compose simple asynchronous functions and how to use try .. with to handle exceptions in asynchronous workflows.

    35 people like this

    Posted: 6 years ago by Tomas Petricek

  • Resource cleanup event combinator

    Declares an event combinator 'Event.using' that automatically releases resources allocated by a previous event occurence. Each event occurence creates a value using a function specified by the user and automatically calls 'Dispose' when generating a new value.

    2 people like this

    Posted: 6 years ago by Tomas Petricek

  • General power function with units

    The snippet demonstrates how to write a general power function that has correct type involving units-of-measure. The function uses numbers represented using types. The snippet is mainly an example of what can be done (not recommended for the real world).

    5 people like this

    Posted: 6 years ago by Tomas Petricek

  • Throttling agent

    Agent that can be used for controlling the number of concurrently executing asynchronous workflows. The agent runs a specified number of operations concurrently and queues remaining pending requests. The queued work items are started as soon as one of the previous items completes.

    15 people like this

    Posted: 6 years ago by Tomas Petricek

  • Cancellable agent

    The snippet implements a wrapper for standard F# agent that can be cancelled using the IDisposable interface. This makes it possible to use the agent locally (e.g. inside asynchronous workflow). When it is no longer needed, the agent's body is cancelled.

    11 people like this

    Posted: 6 years ago by Tomas Petricek

  • Extensions for HTTP servers

    This snippet extends several types from the System.Net namespace. It provides an easy to use API for creating asynchronous (as well as synchronous) HTTP servers using F# asynchronous workflows.

    4 people like this

    Posted: 6 years ago by Tomas Petricek

  • Asynchronous HTTP proxy with chunking and caching

    This snippet shows two improvements to asynchronous HTTP proxy from: http://fssnip.net/6e. First extension is to process page in chunks (instead of downloading the entire content first). The second extension is to use simple agent-based in-memory cache for previously visited pages.

    6 people like this

    Posted: 6 years ago by Tomas Petricek

  • Seq.reduceBallanced function

    The function has the same type as Seq.reduce. Instead of reducing elements from the left to the right, it splits the input into two halves, reduces each half separately and then aggregates the results using the given function. This means that the values are aggregated into a ballanced tree, which can save stack space.

    2 people like this

    Posted: 6 years ago by Tomas Petricek

  • Download stock prices as async sequence

    The snippet uses asynchronous sequences (from F# AsyncExtensions) to download historical stock data from Yahoo. Data is downloaded in a buffered way on demand (as needed) and returned line by line. The sample then prints OHLC values for first 30 items.

    6 people like this

    Posted: 6 years ago by Tomas Petricek

  • Sliding window for Observable

    Implements the Observable.windowed function that creates an observable returning a sliding window. The function is an observable version of Seq.observable. The implementation uses a simple F# agent that keeps partial windows and sends them to an observer.

    4 people like this

    Posted: 6 years ago by Tomas Petricek

  • Memoization for dynamic programming

    The snippet shows how to implement reusable memoization function and how to use it to implement efficient Fibonacci number generator using dynamic programming.

    4 people like this

    Posted: 5 years ago by Tomas Petricek

  • Non-deterministic computation builder

    Computation builder for writing non-deterministic computations.

    8 people like this

    Posted: 5 years ago by Tomas Petricek

  • DSL for financial contracts

    Simple domain-specific language (DSL) for describing financial contracts in F#. A contract is represented using a discriminated union. Evaluating a contract gives the orders that may happen at a given date.

    7 people like this

    Posted: 5 years ago by Tomas Petricek

  • Nest items of a sequence

    A function that nests items of a sequence that do not match a specified predicate under the last item that matches the predicate. The input is a sequence of values and the result is a sequence of pairs where the second element is a list of nested items.

    3 people like this

    Posted: 5 years ago by Tomas Petricek

  • Expanding quotations

    The snippet implements a function "expand" that takes a quotation and performs two operations. It replaces all calls to methods marked with ReflectedDefinition with the body of the method and it simplifies all expressions that can be reduced in call-by-name style (let binding & application of lambda).

    5 people like this

    Posted: 5 years ago by Tomas Petricek

  • Finalizing Tesco purchase

    The sample shows two different reprezentations of Tesco checkout. The first one stores scanned items - as a list of either purchase or cancel items - and the second stores final bill with product and total quantity. The snippet implements transformation that corresponds to finalizing the purchase.

    3 people like this

    Posted: 5 years ago by Tomas Petricek

  • DSL for Price Patterns (Setup)

    Domain-specific language for detecting patterns in stock prices. Run using try F#.

    4 people like this

    Posted: 5 years ago by Tomas Petricek

  • Translating quotations to LINQ

    A sample that translates simple F# quotations (method calls, property getters) to stnadard C# LINQ expression trees.

    7 people like this

    Posted: 5 years ago by Tomas Petricek

  • Processing Prices & Charting (Setup)

    Implements simple library for downloading Yahoo stock prices and displaying charts in Try F#. This snippet loads another one with examples.

    2 people like this

    Posted: 5 years ago by Tomas Petricek

  • Yet Another Financial Contracts (Setup)

    Yet another tutorial based on the DSL for modelling financial contracts. This part just loads library for downloading prices & loads another snippet. Designed to run in Try F#.

    0 people like this

    Posted: 5 years ago by Tomas Petricek

  • Calculate PI using Monte Carlo

    Simple walkthrough that demonstrates how to estimate the value of PI using Monte Carlo simulation. A few holes need to be filled in and then you can run & parallelize the sample!

    4 people like this

    Posted: 5 years ago by Tomas Petricek

  • Reporting events from agents

    This snippet shows different options for reporting events from an F# agent. The options include triggering the event directly, using a thread pool or using a specified synchronization context.

    0 people like this

    Posted: 5 years ago by Tomas Petricek

  • Asynchronous cancellation of a workflow

    The snippet implements Async.StartCancellable method that can be used to start a given workflow and then cancel it. The cancellation of the workflow is done asynchronously, which means that the caller will wait until the workflow is actually cancelled.

    4 people like this

    Posted: 5 years ago by Tomas Petricek

  • Partition a list

    The snippet implements 'List.partitionWhile' which behaves as a combination of 'Seq.takeWhile' and 'Seq.skipWhile': It splits the list into a part containing elements from the beginning of a list that match a given predicate and remaining elements.

    5 people like this

    Posted: 5 years ago by Tomas Petricek

  • Slicing for Math.Net vectors and matrices

    This snippet adds the 'GetSlice' operation to Math.Net vector and matrix types. This makes it possible to get sub-vectors and sub-matrices using the convenient syntax (For vectors 'vect.[start .. end]` or 'vect.[start ..]' and for matrices 'mat.[r1 .. r2, c1 .. c2]' and similar).

    9 people like this

    Posted: 5 years ago by Tomas Petricek

  • Substituting names

    An example that shows how we can represent unique names (using classes) and how to substitute names in any F# type type defined using records, discriminated unions and tuples.

    0 people like this

    Posted: 4 years ago by Tomas Petricek

  • DSL for constructing HTML

    Just another DSL for creating HTML in F#. This DSL attempts to have nice syntax using curly brackets (F# computation expression blocks) for nesting. It does not use other keywords like `yield` (to keep the syntax as non-intrusive as possible), but that means the implementation relies on mutation. I think there could be nicer implementation using automatic quoting in F# 3.0.

    14 people like this

    Posted: 4 years ago by Tomas Petricek

  • Async function that retries work

    A simple asynchronous workflow that retries running a given async workflow (until "resultOk" function returns true or until a specified number of retries is performed). The function uses tail-recursion in async workflows.

    6 people like this

    Posted: 4 years ago by Tomas Petricek

  • Finalizable function object

    The snippet shows how to create an F# function value that will call a custom finalizer function when garbage collected. This is done by creating a type that inherits from FSharpFunc.

    8 people like this

    Posted: 4 years ago by Tomas Petricek

  • Course 1: World bank

    F# introduction course - Exploring World Bank data in Try F#

    0 people like this

    Posted: 4 years ago by Tomas Petricek

  • Course 3: Exploring Titanic dataset

    F# introduction course - Getting data about Titanic passengers using CSV type provider and analyzing them using standard sequence-processing functions known from LINQ. To be used in Try F#.

    1 people like this

    Posted: 4 years ago by Tomas Petricek

  • Structural XML reader

    A simple library that reads XML documents into user-defined F# types. The user defines a set of discriminated unions that model the elements of the file and a library automatically creates these types from a XML file.

    8 people like this

    Posted: 4 years ago by Tomas Petricek

  • Display digit

    A function to display digit from ML coding Dojo by Mathais

    0 people like this

    Posted: 4 years ago by Tomas Petricek

  • Implement interface by expression

    What feature would I like to see in F#? One thing is the ability to implement an interface in a class by delegating the implementation to an expression. This snippet demonstrates the idea using a simple example of vectors.

    7 people like this

    Posted: 4 years ago by Tomas Petricek

  • xBehave Quickstart with computation builders

    Another version of the xBahve quick start example, this time using custom F# computation builder to make the code nicer. We define a builder for step and custom functions for Given/And/When/Then.

    3 people like this

    Posted: 4 years ago by Tomas Petricek

  • Initialization of 2D array that may fail

    A function to initialize 2D array that supports failures - if the initializer fails to produce value for any of the array locations, the construction is stopped and the function returns 'None'

    3 people like this

    Posted: 3 years ago by Tomas Petricek

  • Create frame from dictionaries

    A simple example that creates a frame from a list of dictionaries. Each dictionary is treated as a row that maps column keys to values. The trick is to use Deedle value expansion.

    1 people like this

    Posted: 3 years ago by Tomas Petricek

  • Is 1.0 identity element of multiplication?

    A simple script that checks whether 1.0 is really the identity element of multiplication for 32bit floating-point numbers.

    0 people like this

    Posted: 3 years ago by Tomas Petricek

  • Generating numerical ranges

    Different ways of generating numerical ranges in F#. It turns out that the built-in syntax generates fairly slow code, so the snippet shows two alternative ways that are faster. Any compiler optimizations making the built-in one faster would be nice :-)

    6 people like this

    Posted: 3 years ago by Tomas Petricek

  • Get entity names from Freebase type provider

    This sample uses the internals of the Freebase type provider to get the names of all the entities that Freebase knows about. The snippet returns the type names, so some of the type provider internals are exposed, but it still returns nice list of entities.

    0 people like this

    Posted: 3 years ago by Tomas Petricek

  • Agent demo

    Agent demo

    9 people like this

    Posted: 3 years ago by Tomas Petricek

  • Throttling agent

    Implements a simple agent that lets you throttle the degree of parallelism by limiting the number of work items that are processed in parallel.

    6 people like this

    Posted: 2 years ago by Tomas Petricek

  • Simple validation using functions

    This is a "library" for validation that collects all validation errors (and does not use the heavy-weight machinery of monads). This is perhaps a simpler variant that could be used e.g. here: http://tinyurl.com/lv2nwkl

    3 people like this

    Posted: 2 years ago by Tomas Petricek

  • Extract info from F# Compiler Service exceptions

    When you get an exception from the F# Compiler Service, it usually does not print any useful information. But you can look at the private fields of the exception and get some more useful things out of it...

    0 people like this

    Posted: 2 years ago by Tomas Petricek

  • Fun3D Castle

    3D castle sample from the Fun3D project, now written using WebGL and running in a web browser...

    2 people like this

    Posted: 2 years ago by Tomas Petricek

  • Parse UNIX time stamp

    Parses UNIX time stamp into DateTime (as returned for example by the OpenWeatherMap API)

    3 people like this

    Posted: 2 years ago by Tomas Petricek

  • "99 OCaml" #83 Sudoku solver

    Every spot in the puzzle belongs to a (horizontal) row and a (vertical) column, as well as to one single 3x3 square (which we call "square" for short). At the beginning, some of the spots carry a single-digit number between 1 and 9. The problem is to fill the missing spots with digits in such a way that every number between 1 and 9 appears exactly once in each row, in each column, and in each square.

    2 people like this

    Posted: 2 years ago by Tomas Petricek

  • APL mode for F#

    Inspired by @theburningmonk, this snippet defines a couple of extensions and operators that can be used to make F# as short and as obscure as APL. Complete with a 19 character solution of the Euler problem #1!

    5 people like this

    Posted: 2 years ago by Tomas Petricek

  • Reinventing the Reader Monad

    Alternative solution to the problem in Scott Wlaschin's "Reinventing the Reader Monad" article (but without monads).

    1 people like this

    Posted: 2 years ago by Tomas Petricek

  • Flappy bird with sequence expressions

    This is a somewhat sensible solution to the flappy bird dojo by Phil Trelford. It uses sequence expressions eliminate some mutation of the flappy bird. To play this sample on Windows simply copy the code from the raw view and execute in F# interactive, for cross platform implementations check out: http://trelford.com/prognet15.zip

    6 people like this

    Posted: 2 years ago by Tomas Petricek

  • Hello

    im in ur forms, updating ur snippets!

    0 people like this

    Posted: 2 years ago by Tomas Petricek

  • Chart NuGet package downloads

    Quick script using FsLab that visualizes the aggregate number of downloads of a NuGet package over time, using the HTML type provider to get the data from www.nuget.org.

    2 people like this

    Posted: 1 years ago by Tomas Petricek

  • Choose while function

    A function that is like 'Seq.choose' but stops producing values as soon as the first 'None' value is produced.

    3 people like this

    Posted: 1 years ago by Tomas Petricek

  • F# Data type providers

    Reading the F# snippets RSS feed using the F# Data XML type provider. Look, you now get tool tips for type providers too!

    1 people like this

    Posted: 1 years ago by Tomas Petricek

  • Solving 8 queens problem with F#

    Solve the 8 queens problem in F#, keeping available positions on the board as a list of X,Y coordinates.

    2 people like this

    Posted: 1 years ago by Tomas Petricek

  • Most popular F# tools and libraries

    Analyze results of the fsharpWorks annual F# community survey to figure out what are the most popular F# tools and libraries. The snippet does some minimal data cleanup, but more work is needed to get precise results!

    1 people like this

    Posted: 1 years ago by Tomas Petricek

  • The Missing #Rio2016 REST API

    The snippet shows how to extract list of Olympic medalists from the Rio 2016 web site in a nice JSON format. It turns out you just need the right regular expression to extract the data from a script tag...

    2 people like this

    Posted: 1 years ago by Tomas Petricek

  • F# snippet formatting service

    Do you want to format F# snippets, but cannot easily run the F# Formatting library as part of your documentation processing? We just added F# Formatting as a service (FAAS!) API to the F# Snippets. This code snippet shows how to call the service.

    2 people like this

    Posted: 1 years ago by Tomas Petricek