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.

    76 people like this

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

    185 people like this

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

    42 people like this

    Posted: 13 years ago by Tomas Petricek

  • Support slicing operator

    The snippet shows how to support slicing in a type. Slicing allows you to get for example a 2D sub-matrix of a matrix and is implemented by adding GetSlice member.

    49 people like this

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

    84 people like this

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

    26 people like this

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

    36 people like this

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

    34 people like this

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

  • Line 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 Line chart. The sample generates a 2D spline calculated using sin and cos functions.

    11 people like this

    Posted: 13 years ago by Tomas Petricek

  • Boxplot diagram 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 BoxPlot diagram. In this sample, we provide six statistics (Maxmimum, Minimum, Upper quartile, Lower quartile, Average and Median) about observations explicitly.

    23 people like this

    Posted: 13 years ago by Tomas Petricek

  • Imperative computation builder

    Defines an F# computation builder for encoding imperative computations. The 'return' construct returns immediately and terminates the rest of the computation. It is also possible to return value from a 'for' or 'while' loop.

    11 people like this

    Posted: 13 years ago by Tomas Petricek

  • Asynchronous Controller Helper

    The snippet declares a helper for creating asynchronous controllers for ASP.NET MVC 3. It declares a new base class for asynchronous actions that exposes a computation builder for writing actions using F# asynchronous workflows.

    8 people like this

    Posted: 13 years ago by Tomas Petricek

  • WebSharper Hello World

    This sample implements "Hello, world!" as a WebSharper application. It demonstrates how to compose HTML/XML using combinators, how to dynamically create a button with a handler and how to update an existing DOM element.

    4 people like this

    Posted: 13 years ago by Tomas Petricek

  • All subsets of a set

    A function implemented using sequence expressions that returns all subsets of a specified set. The function is not optimized, but it is very easy to understand.

    11 people like this

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

    6 people like this

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

  • Non-deterministic computation builder

    Computation builder for writing non-deterministic computations.

    8 people like this

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

    8 people like this

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

    3 people like this

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

    24 people like this

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

  • Course 1: World bank

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

    0 people like this

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

  • Display digit

    A function to display digit from ML coding Dojo by Mathais

    0 people like this

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

  • Agent demo

    Agent demo

    12 people like this

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

  • Hello

    im in ur forms, updating ur snippets!

    0 people like this

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

    7 people like this

    Posted: 5 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: 4 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.

    3 people like this

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

  • Web Crawler extensions

    The snippet extends a web crawler from snippet http://fssnip.net/3K. It synchronizes all printing using an additional agent (so printed text does not interleave) and the crawling function returns an asynchronous workflow that returns when crawling completes.

    0 people like this

    Posted: 1 year ago by Tomas Petricek

  • Interact monad

    Interactive computation that asks the user questions

    9 people like this

    Posted: 5 months ago by Tomas Petricek