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.
39 people like this
Posted: 1 years ago by Tomas PetricekProjecting lists
Three functions showing how to implement projection for functional lists. First version uses naive recursion and the second one is tail-recursive using the accumulator parameter. The third version extends this with continuation passing.
43 people like this
Posted: 1 years ago by Tomas PetricekRandom 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.
22 people like this
Posted: 1 years ago by Tomas PetricekForm changing color
Windows Forms tutorial showing how to create form with button and how to register an event handler. When the button is clicked, the form changes its background color.
29 people like this
Posted: 1 years ago by Tomas PetricekHello world (F#)
Classical "Hello world" example that prints a message to the console output. This version uses F# printfn function to do the printing.
131 people like this
Posted: 1 years ago by Tomas PetricekHello world (.NET)
Classical "Hello world" example that prints a message to the console output. This version uses .NET Console.WriteLine method to do the printing.
23 people like this
Posted: 1 years ago by Tomas PetricekFriendly 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".
26 people like this
Posted: 1 years ago by Tomas PetricekPipeline list processing
An example showing how to process list in a pipeline. We first use List.filter to return only even numbers and then use List.map to format them as strings.
76 people like this
Posted: 1 years ago by Tomas PetricekNice 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.
13 people like this
Posted: 1 years ago by Tomas PetricekSupport 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.
37 people like this
Posted: 1 years ago by Tomas PetricekCompiling 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.
40 people like this
Posted: 1 years ago by Tomas PetricekWinForms 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.
17 people like this
Posted: 1 years ago by Tomas PetricekCreating 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.
53 people like this
Posted: 1 years ago by Tomas PetricekWorking 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.
9 people like this
Posted: 1 years ago by Tomas PetricekTraverse 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.
13 people like this
Posted: 1 years ago by Tomas PetricekAsynchronous sequences
An asynchronous sequence is similar to the seq<T> type, but the elements of the sequence are generated asynchronously without blocking the caller as in Async<T>. This snippet declares asynchronous sequence and uses it to compare two files in 1k blocks.
36 people like this
Posted: 1 years ago by Tomas PetricekTake 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.
19 people like this
Posted: 1 years ago by Tomas PetricekActive 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.
49 people like this
Posted: 1 years ago by Tomas PetricekFind 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.
8 people like this
Posted: 1 years ago by Tomas PetricekDisposable 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.
27 people like this
Posted: 1 years ago by Tomas PetricekDynamic 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.
25 people like this
Posted: 1 years ago by Tomas PetricekDynamic 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.
41 people like this
Posted: 1 years ago by Tomas PetricekEnumerator 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.
25 people like this
Posted: 1 years ago by Tomas PetricekBar 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.
17 people like this
Posted: 1 years ago by Tomas PetricekDoughnut 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.
46 people like this
Posted: 1 years ago by Tomas PetricekLine 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.
9 people like this
Posted: 1 years ago by Tomas PetricekCandlestick 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.
9 people like this
Posted: 1 years ago by Tomas PetricekBoxplot 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.
14 people like this
Posted: 1 years ago by Tomas PetricekSimple asynchronous functions
The snippet demonstrates how to compose simple asynchronous functions and how to use try .. with to handle exceptions in asynchronous workflows.
28 people like this
Posted: 1 years ago by Tomas PetricekImperative 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.
6 people like this
Posted: 1 years ago by Tomas PetricekResource 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: 1 years ago by Tomas PetricekAsynchronous 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.
7 people like this
Posted: 1 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: 1 years ago by Tomas PetricekWebSharper 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.
2 people like this
Posted: 12 months ago by Tomas PetricekThrottling 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.
9 people like this
Posted: 11 months ago by Tomas PetricekAll 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.
8 people like this
Posted: 11 months ago by Tomas PetricekCancellable 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.
8 people like this
Posted: 10 months ago by Tomas PetricekWeb 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.
6 people like this
Posted: 10 months ago by Tomas PetricekExtensions 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.
3 people like this
Posted: 10 months ago by Tomas PetricekSynchronous, event-based and asynchronous HTTP proxy
This snippet shows the implementation of three HTTP proxy servers in F#. The first is written using simple synchronous style (that isn't scalable). The second version uses event-based approach in the Node.js style, but is difficult to write. The third version uses F# async workflows and is both scalable and easy to write.
5 people like this
Posted: 10 months ago by Tomas PetricekAsynchronous 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.
5 people like this
Posted: 10 months ago by Tomas PetricekSeq.groupWhen function
The snippet declares a function that groups adjacent elements of a sequence. A new group is started when the specified predicate holds about an element. Groups are constructed eagerly (using lists).
4 people like this
Posted: 10 months ago by Tomas PetricekReturn the first result using Async.Choice
The snippet implements Async.Choice method that takes several workflows and creates a workflow, which returns the first result that was computed. After a workflow completes, remaining workflows are cancelled using the F# async cancellation mechanism. (The method doesn't handle exceptions.)
6 people like this
Posted: 9 months ago by Tomas PetricekSeq.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: 9 months ago by Tomas PetricekAsyncSeq - Introduction and Crawler
This snippet demonstrates programming using asynchronous sequences. It contains (hidden) implementation of AsyncSeq type and combinators for working with it. More importantly, it demonstrates how to use asynchronous sequences to implement a simple sequential on-demand crawler.
8 people like this
Posted: 9 months ago by Tomas PetricekDownload 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.
5 people like this
Posted: 8 months ago by Tomas PetricekCreating observable using Async.StartDisposable
Implements a simple Async.StartDisposable extension that can be used to easily create IObservable values from F# asynchronous workflows. The method starts an asynchronous workflow and returns IDisposable that cancels the workflow when disposed.
4 people like this
Posted: 8 months ago by Tomas PetricekSliding 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.
3 people like this
Posted: 8 months ago by Tomas PetricekAsync.Choose operation
Non-deterministic choice operation for F# asynchronous workflows - creates a workflow that returns the result of one of two asynchronous workflows, depending on which completes first. (The other workflow is not cancelled.)
3 people like this
Posted: 7 months ago by Tomas PetricekMemoization 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.
1 people like this
Posted: 6 months ago by Tomas PetricekCaching agent
Agent that keeps a cache of web pages that were downloaded previously. The agent handles messages to add and get data as well as message to clear the cache.
2 people like this
Posted: 6 months ago by Tomas PetricekNon-deterministic computation builder
Computation builder for writing non-deterministic computations.
7 people like this
Posted: 6 months ago by Tomas PetricekUniversity enrollment (CZE vs. EU)
Using World Bank type provider and FSharpChart to show average university enrollment in Czech Republic, European Union and OECD members.
6 people like this
Posted: 6 months ago by Tomas PetricekDSL 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.
6 people like this
Posted: 5 months ago by Tomas PetricekF# counter agent
The snippet shows a simple F# agent that calculates average from the received values. It supports one message for adding numbers to the statistics and one for resetting the state. Moreover, the agent limits the processing rate to 1 message per second.
3 people like this
Posted: 4 months ago by Tomas PetricekNest 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: 4 months ago by Tomas PetricekSend HTTP POST request
The snippet shows how to send HTTP POST request to a web page and download the generated HTML result. The POST data is encoded as a byte array and written to the request stream of HttpWebRequest.
2 people like this
Posted: 3 months ago by Tomas PetricekExpanding 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).
1 people like this
Posted: 1 months ago by Tomas PetricekTesco in 70 lines of code
Domain model for the Tesco checkout implemented in F# using discriminated unions (in 20 lines of code) and console-based user interface for scanning products and calculating the total price.
3 people like this
Posted: 1 months ago by Tomas PetricekFinalizing 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: 1 months ago by Tomas PetricekDSL for Financial Contracts
Simple domain-specific language for modeling of financial contracts.
6 people like this
Posted: 27 days ago by Tomas PetricekDSL for Price Patterns (Setup)
Domain-specific language for detecting patterns in stock prices. Run using try F#.
3 people like this
Posted: 27 days ago by Tomas PetricekDSL for Price Patterns (Demo)
Examples that use domain-specific langauge for detecting price patterns. To run the sample, load the previous snippet in TryF#. It opens the sample automatically.
2 people like this
Posted: 27 days ago by Tomas Petricek