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.

    72 people like this

    Posted: 12 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.

    39 people like this

    Posted: 12 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.

    183 people like this

    Posted: 12 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".

    39 people like this

    Posted: 12 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.

    21 people like this

    Posted: 12 years ago by Tomas Petricek

  • WinForms layout combinators

    A domain specific language for creating layout using Windows Forms. The snippet implements combinators for creating controls and simple automatic arrangement of them.

    42 people like this

    Posted: 12 years ago by Tomas Petricek

  • Working with paths

    Concatenating paths shouldn't be done just using string concatenation, because the directory separator may differ on various platforms. This snippet shows a simple custom operator for working with paths.

    26 people like this

    Posted: 12 years ago by Tomas Petricek

  • Asynchronous sequences

    An asynchronous sequence is similar to the seq type, but the elements of the sequence are generated asynchronously without blocking the caller as in Async. This snippet declares asynchronous sequence and uses it to compare two files in 1k blocks.

    109 people like this

    Posted: 12 years ago by Tomas Petricek

  • Active pattern for let binding inside patterns

    The Let active pattern demonstrated by this snippet can be used to assign values to symbols in pattern matching. This is useful for writing complex pattern matching using match as we can handle multiple cases using a single clause.

    64 people like this

    Posted: 12 years ago by Tomas Petricek

  • Disposable computation builder

    Computation builder that provides easy way of constructing IDisposable objects. It supports elegant composition of disposable objects using 'do!' which can be used for example when working with 'IObservable' type.

    42 people like this

    Posted: 12 years ago by Tomas Petricek

  • Dynamic operator using Reflection

    Demonstrates how to implement the dynamic operator (?) using .NET Reflection. The implementation supports calling constructors, propreties and methods using simple overload resolution (based on parameter count). It handles instance as well as static members.

    71 people like this

    Posted: 12 years ago by Tomas Petricek

  • Bar 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 Bar chart. The sample shows population sizes in different continents.

    23 people like this

    Posted: 12 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: 12 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: 12 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: 11 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: 11 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.

    20 people like this

    Posted: 11 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: 11 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: 11 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.

    7 people like this

    Posted: 11 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: 11 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: 11 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.

    5 people like this

    Posted: 11 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.

    6 people like this

    Posted: 11 years ago by Tomas Petricek

  • Non-deterministic computation builder

    Computation builder for writing non-deterministic computations.

    8 people like this

    Posted: 11 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: 11 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: 11 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).

    7 people like this

    Posted: 10 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: 10 years ago by Tomas Petricek

  • DSL for Price Patterns (Setup)

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

    5 people like this

    Posted: 10 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: 10 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: 10 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: 10 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: 10 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.

    2 people like this

    Posted: 10 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.

    6 people like this

    Posted: 10 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.

    7 people like this

    Posted: 10 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: 10 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: 10 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.

    17 people like this

    Posted: 10 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.

    7 people like this

    Posted: 10 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: 9 years ago by Tomas Petricek

  • Course 1: World bank

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

    0 people like this

    Posted: 9 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: 9 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.

    10 people like this

    Posted: 9 years ago by Tomas Petricek

  • Display digit

    A function to display digit from ML coding Dojo by Mathais

    0 people like this

    Posted: 9 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: 9 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: 9 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: 9 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: 8 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: 8 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: 8 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: 8 years ago by Tomas Petricek

  • Agent demo

    Agent demo

    12 people like this

    Posted: 8 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.

    7 people like this

    Posted: 8 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

    7 people like this

    Posted: 8 years ago by Tomas Petricek

  • Hello world

    A very simple function to print hello world, which is completely useless. Just testin the F# Snippets API...

    1 people like this

    Posted: 7 years ago by Tomas Petricek

  • Helpers for formatting dates and strings

    Simplistic helpers for formatting dates and strings in a web server (strip HTML tags when reading RSS feeds, nicely format dates etc.)

    2 people like this

    Posted: 7 years ago by Tomas Petricek

  • DotLiquid integration with Suave

    Example of integrating DotLiquid with a simple Suave server. The snippet automatically registers all public members of a record as members that can be accessed by DotLiquid templates.

    5 people like this

    Posted: 7 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!

    7 people like this

    Posted: 7 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).

    3 people like this

    Posted: 7 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: 7 years ago by Tomas Petricek

  • Hello

    im in ur forms, updating ur snippets!

    0 people like this

    Posted: 7 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: 7 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: 7 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: 6 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: 6 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: 6 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: 6 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: 6 years ago by Tomas Petricek

  • Phantom type example

    The snippet shows a minimal example of phantom types for type-safe way of tracking different types of IDs in a simple system.

    6 people like this

    Posted: 3 years ago by Tomas Petricek

  • 10 PRINT CHR$(205.5+RND(1)); : GOTO 10

    Inspired by https://10print.org, this is a small incomplete BASIC interpreter that can generate a maze.

    5 people like this

    Posted: 2 years ago by Tomas Petricek

  • 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.

    1 people like this

    Posted: 1 year ago by Tomas Petricek

  • Capture the rest of sequence on error

    Computation expression that automatically captures the rest of the sequence that you are iterating over using a "for" loop so that the exception handler can do something clever with it.

    0 people like this

    Posted: 1 year ago by Tomas Petricek