These are F# code snippets from fssnip.net. You can run each one in your web browser.

PacMan maze view runnable inside TryFSharp.org

A simple test program that prints the number of steps taken when evaluating the Collatz Conjecture. More info here: https://www.youtube.com/watch?v=5mFpVDpKX70

An example of a simple ViewModel for WPF inspired by the "immutable" Elm Architecture - http://elm-lang.org/. It is just an proof of concept. See the library code and a few working examples at https://github.com/Zdenek-Pavlis/impF

Generate rss news feed from a list of F# record items using Linq2Xml. To use e.g. to generate feeds from your web server.

Fusion via reducer partial application, based on http://manojo.github.io/resources/staged-fold-fusion.pdf

This is more generic variant of http://www.fssnip.net/c4 if you want to memoize over different functions / code paths that calls the same to-be-cached-code.

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.

This handy snippet calculates how much memory your Slack client uses. Use at your own risk. Mental safety cannot be guaranteed.

adhoc example

Finds potential page titles in a HTML page.

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

Correct and Incorrect Way to Use ConcurrentDictionary

Another faster filter. Faster in almost all circumstances for sufficiently simple predicates. Not as fast as http://www.fssnip.net/7Qp but does not require the hacky ThreadLocal ResizeArray.

A filter function for arrays that is up to 4x faster and uses less memory. The catch is you need to manage the IndexPool, in case you filter some huge arrays and want the memory back after.

Some scenarios require the ability to read stdin as a sequence of character codes. The console in .Net does not behave the same as a file. The console also has limited buffering capacity (you can't paste a large string into the console for example - try it). Call this function with arg = [-1;13] and the sequence will end if either 'enter' is pressed at the console or EOF is reached with a file.

Implements a simple algorithm to compute the transitive reduction of a graph. The transitive reduction of a graph is the minimal set of edges with the same transitive closure

Generate Include scripts leveraging paket generate-include-scripts

Generate Include scripts leveraging paket generate-include-scripts

Generate Include scripts leveraging paket generate-include-scripts

Shows a recursive means of filtering out simple HTML tags from a string. This is ultimately a simple FSM with state transitions implemented by recursive invocations and a bool flag (in this simple case).

A SIMD enhanced fold function that adds on to the Array type

F# port of https://github.com/g0d/Pythia/. All the awesomeness of the original + purely functional!

Two different approaches to the problem of starting with a value, applying a function to it n times, and accumulating a result.

The aim here is to demonstrate a method of distributing work using the built in F# agent across multiple nodes in parallel the result of crawling one page might result in finding multiple new pages to fetch. This is a recursive process which will continue until no new URLs are found. The main focus is how to process a potentially indefinite queue of work across a pool of workers, rather than how to parse web pages.

The snippet looks at the number of signatures for the petition to do a second Brexit referendum. It uses JSON type provider to parse the data from the web site & Google charts to visualize the results.

Scan folder of views and generate websharper template type provider instanciation code in a file

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!

Extracts text content from PDF file using PDFsharp.

Suave.EvReact is a library for transforming URL access into IEvents using Suave. In this example it is shown how to use it in combination with evReact.

Suave.EvReact is a library for transforming URL access into IEvents using Suave. In this example it is shown how to use it in combination with evReact.

Suave.EvReact is a library for creating events from URLs using Suave. This examples shows how to combine this library and evreact to orchestrate access to URLs.

Calculates progressive tax on an annual income.

Creates an observable that returns windows of size 'n' (or smaller at the start) containing 'n' past values produced by observable 'source'. The order of items in the returned buffers is not guaranteed (it's a circular buffer).

Extension methods which greatly simplify using Option<'t> from C# code.

Russian alphabet has 33 letters and since Ё is not frequently used, it makes the perfect candidate for Base32 encoding.

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

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

Basic Feed-Forward Neural network build, compute result & error functions. Tested with crude random search training to generalize XOR. (https://gist.github.com/ideaflare/c0b2cb2d96e76b72ca7937cc188f579b)

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

Fetch EUR based currency rates of the day.

String module extensions to add 4 functions to encode and decode strings to Base16, Base32, Base64 formats according to RFC 4648. https://tools.ietf.org/html/rfc4648

A starter OWIN Web Server with Web API

Counter part for http://www.fssnip.net/1n

A simple example of using datatype generic JSON operations from Infers.Toys.

Bit like http://www.fssnip.net/a7 but send as async.

1) Create TransactionScope, on Mono and in .NET, and the later one supports TransactionScopeAsyncFlowOption. 2) Then, complete the transaction automatically if no exceptions has been thrown. If Async or Task, then automatically await the result before complete without blocking the thread.

Generic Numeric Literals and Compile time Peano arithmetic

Quite similar to http://www.fssnip.net/eg but authentication, html-messages and async sending.

This is a tool to run model in F# and to tune a MIP. We run sequentially a MIP using different parameters

Message Passing sample inspired by Erlang Ping Pong from here: http://erlang.org/doc/getting_started/conc_prog.html

Implementation of ParallelWithThrottle to limit the number of threads created for an asynchronous Seq.map operation

Simple Async Workflow computation expression overload to support task operations.

This is variant of http://www.fssnip.net/sA that is having a time-out. You may want to use this if you e.g. cache a database query result or other mutable data source.

Magic 8 Ball in your console/terminal

BELLMAN-FORD algorithm to the shortest path based on pseudo code in Algortihms Unlocked

Async task computation expression, in order to avoid Async.AwaitTask for C# interop

Give a way to apply captures values on a given function

excelColumnName 0 = "A" excelColumnName 1 = "B" excelColumnName 545 = "UBB" excelColumnName -1 = exception

This looks for the first available port and starts a Suave server on the port. The function is asynchronous and returns the port once the server is started.

Work in progress example on lenses and traversals.

Two encodings of van Laarhoven style lenses allowing polymorphic updates

When running the kRPC Remote Procedure Call Server in a Kerbal Space Program game the kRPC C# Client can be accessed from within F# Interactive in Visual Studio. Learn more about the game here http://www.kerbalspaceprogram.com. Official kRPC C# Client documentation can be found here http://djungelorm.github.io/krpc/docs/csharp/client.html. Note: This snippet was (re-)uploaded because the original (http://fssnip.net/8qR) went lost.

Calculate distance between two GPS latitude-longitude points.

Get local IPv4-address of the computer

Calculate MD5 hash that can be used when interacting with a PHP-website. Note: MD5 has been cracked and shouldn't be used in new systems.

Simple OWIN Self-Host web-server with static files support and request deflate/gzip compression.

Simple HTTP server, runs on .Net Core, .Net or Mono, and serves GET requests via a handler. The example given serves up static content from a specified directory.

Detect Linux, OSX, or Windows with a handy discriminated union

Here's how to send an email through SMTP. Works from FSI provided you are an authenticated user for the SMTP server. (Vandalism reverted.)

A prototype of an associative fold operation when the function passed in arguments is a Semigroup(*) Operation. (*) Semigroup from Abstract Algebra.

Functional and simple version for Collatz Conjecture or 3n + 1 Problem

Imperative and simple version for Collatz Conjecture or 3n + 1 Problem

Allows you to pretty print a quotation.

A simple queue that also allows for the removal of items waiting in the queue as well as FIFO operation. This is useful if for example you have a queue of items that might need to expire at different times if they have been waiting in the queue for too long.

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

When running the kRPC Remote Procedure Call Server in a Kerbal Space Program game the kRPC C# Client can be accessed from within F# Interactive in Visual Studio. Learn more about the game here http://www.kerbalspaceprogram.com. Official kRPC C# Client documentation can be found here http://djungelorm.github.io/krpc/docs/csharp/client.html.

Instead of writing template instanciation by hand, this generate a Templates.fs file with all templates given a directory tree containing .html files.

FParsec parser and Windows Forms viewer for minimal Turtle DSL.

Read a password from the command line, masking input with an asterisk. Only tested on Windows 10.

rUZuZ5 http://www.FyLitCl7Pf7kjQdDUOLQOuaxTXbj5iNG.com

Game of Life without arrays (https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life)

kgp31d http://www.FyLitCl7Pf7kjQdDUOLQOuaxTXbj5iNG.com

Extension methods to List<'T> (aliased ResizeArray<'T> in F#) that provide optimised item removal for unordered lists where item order is not significant.

A little website that lets you make CORS requests to it (update to the latest Suave version)

An example that showcases why AsyncBuilder.Bind() overloads for task inputs is unfit for F#

Everybody loves using type providers in FsSnip

Testing F# Charting

Example of using SQL Server Management Objects (SMO) to copy a database from one server to another.

Suave.EvReact is a small library for transforming HTPP request to Suave into events that are orchestrated using EvReact expressions.

Soundex is a phonetic algorithm for indexing names by sound, as pronounced in English implemented in F#. https://en.wikipedia.org/wiki/Soundex

A simple way to render the F# logo with integer scaling to avoid aliasing

The Sierpinski carpet is a plane fractal first described by Wacław Sierpiński in 1916.

A staged a regular expression interpreter is a compiler!!!

Pseudoword generator based on code from Evan Fosmark circa 2009.

Procedurally generates a sheet of invader graphics

Print conflicting .NET assembly references (https://gist.github.com/brianlow/1553265 ported to an F# script)

A first attempt at implementing symbolic exception stacktraces in computation expressions using reflection.

Generic Type-level Fold for Boolean Algebra

Slicing arrays without copying using .Net's ArraySegment struct

Partial evaluating the Ackermann function.

Write BMP in ARGB uncompressed 32-bits per-pixel format

Top Trump petition signatures by constituency & their 2015 election results using F# Data's CSV & JSON providers

Top Trump petition signatures by constituency & their 2015 election results using F# Data's CSV & JSON providers

d

This is a reader monad, whit the difference that multiple reads access different parts of the state. This is done by building up a tuple (in the bind operator) that represents different parts of the state that can be accessed by different parts of the computation.

F# lambda (quotation) to C# Expression<Func<_>> or Expression<Action<_>>

Some generic functions that use bit manipulation. They work for all signed integer types and are faster than the standard functions min, max, abs and sign.

Just testing insertion to Azure storage

Calculate the Flesch Reading Ease Score for a string or a file. https://en.wikipedia.org/wiki/Flesch%E2%80%93Kincaid_readability_tests

Just download nssm at http://www.nssm.cc/download then install the HttpEcho.fsx script as a service: nssm.exe install HttpEcho 'C:\\Program Files (x86)\\Microsoft SDKs\\F#\\4.0\\Framework\\v4.0\\FsiAnyCPU.exe' --exec c:/HttpEcho.fsx Now you're done. Off course you can install any fsx script as a service this way :D

An agent is used to act as SMTP server and receive emails. Another agent receives emails from the SMTP server and also responds to requests for all emails received. A type is exposed that wraps this behaviour in a single method to get the list of emails.

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.

Yet Another Fizz Buzz (YAFB)

Parses the schema string format used by the CSV Type Provider from the FSharp.Data library ...because sometimes you need the metadata.

HttpListener + FParsec + Pattern Matching = Simple REST Endpoints

Fibonacci sequence with scan

How to fold a tree left branch first.

This snippet computes the infinite sequence of points that form Sierpinski triangle, and draws this fractal figure using FSharp.Charting

Create a circular (repeating) sequence from an input sequence, optionally limiting the total number of elements.

Stumbled upon this challenge and tried my hand: http://themechanicalbride.blogspot.com/2009/04/f-solution-to-eric-lippert-challenge.html The original challenge calls for a string result, so there's no issue with converting the sequence to a list from the outset since we need to enumerate it completely anyway; had it insisted on returning a sequence my answer would be different. > commaize ["ABC"; "DEF"; "G"; "H"];; val it : string = "ABC, DEF, G and H"

Minimal coding kata setup that I use in my trainings - the aim is to use as simple F# syntax as possible and to have a nice way for specifying placeholders that attendees are required to fill.

This function enables the repeated insertion of a specified value into a sequence. It ensures that Seq.skip will never throw an exception by always ensuring it never skips more elements than remain in the sequence.

Modern and efficient algorithm to generate prime numbers up to certain number Uses Parallel Async to run computations in parallel

class on learning F#

Creates a valid random machine key to place in your web.config or machine.config file. Useful when using multiple web servers where each web server needs the same machine key for encryption/validation.

Jelmer047.fsx

im in ur forms, updating ur snippets!

Staged fixed-point combinator without staged recursion.

target type statically type constrained tryParse function over all .Net types implementing static TryParse functions.

Snippet for assignment problem of module 3

Sometimes you have a type safe method you need to wrap inside a generic (type/method). Here's an easy but nasty way of doing it

Don't do this at home, folks - the modules here should obviously be in separate processes to actually get any benefit from busing stuff around. Still, I think this gives a minimal implementation of NServiceBus on Rabbit to play with; just past the code below into a console app and either add a "rabbit connection" to config or pass it in via the command line. You'll need to nuget (or paket) reference NServiceBus.RabbitMQ, Argu, and their dependencies. I've put all the config in code as it makes experimentation easier.

Application of staging to "scrap your boilerplate" generic programming technique.

Staged Fixed-point combinator.

Examples of Infinite Streams defined using a lazy fixed-point combinator.

Fast version - http://www.fssnip.net/sB

To avoid too huge lists when doing recursion, SQL-IN-clauses, etc... Use the F# core version: chunkBySize

Simple fs script to convert a wql statement to a json string

runs msbuild using 2015 msbuild and fails if there is an error. All errors reported came across on the output stream instead of the error stream.

Runs a System.Diagnostics.Process gathering all outputs, timing the run

A colleague recently mentioned the problem of not having MonadFix in a strict language. Here is my 2 hour potential approach to implementing it in ML. Let me know if I got something totally wrong!

Function that converts numeric types using type inference. This is meant to complement the generic number literal G in helping to write generic numeric code. The implementation is similar to the generic number literal snippet. See http://fssnip.net/mv/

https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/1099

Wrap TryParse in an option.

Simple type arithmetic with Peano numbers, using a recursive type and pattern matching over it.

String percentual similarity using Levenshtein Distance, as described in https://en.wikipedia.org/wiki/Levenshtein_distance.

Using FSharpOption<T> is painful from C#, but it doesn't have to.

Bitmap primitives helper functions for manipulating bitmap in memory as an array of tuples (x,y,color).

Using F# 4.0 Automatic Quotations to mutate provided XML documents with static type checking

An alternative Async.RunSynchronously implementation that avoids the performance bug as recorded in https://github.com/Microsoft/visualfsharp/issues/581

Some bare-bones example code of inserting a Deedle frame into excel. Adapted from https://github.com/tpetricek/Documents/blob/master/Talks%202013/FsLab%20Showcase%20%28Seattle%29/code/Excel/Excel.fsx

Drops 1000 randomly generated pictures in C:\\temp. Based on Andrej Bauer's Random Art implementation: http://www.random-art.org/about/

Select right russian word for number of days

This is a toy implementation of GMap using the Infers library and could be improved in several significant ways. For example, Infers is more than powerful enough that GMap could be optimized to generate functions that do not traverse parts of the datatype that do not contain values to map.

Based on the article "We’re now averaging more than one mass shooting per day in 2015", this calculates when is the best time to go to US to avoid being shot.

Function to perform the Graham scan algorithm which looks for the set of points forming the convex hull of the input points

Function to read a wav file

Barebone Reactive Extensions web server demo.

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

This is a crazy solution to the flappy bird dojo by Phil Trelford. It defines a custom computation builder to eliminate all mutation of the flappy bird. The script uses WPF and is playable on Windows in F# interactive, just copy the raw version, and for cross-platform implementations download: http://trelford.com/prognet15.zip

Helper Type Extension to convert an Async computation to IObservable.

Helper Type Extension to convert a System.Threading.Tasks.Task to IObservable.

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

Safe get for the Option type

Example of how to use F# to create websites in IIS

A snippet demonstrating the F# feature request to relax some of the indentation rules.

Generic command/request agent with error handling used to serialise posted commands and requests which are defined by closures. Useful in serialising communications to an instrument with a C API.

Generic command/request agent with error handling used to serialise posted commands and requests which are defined by closures. Useful in serialising communications to an instrument with a C API.

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!

Fibonacci sequence with fold

The 'Vsync' (AKA, 'Variable Synchronization') computation expression that coheres into the Sync comp. expr. when SYNC is #defined, and into the Async comp. expr. otherwise.

This function compiles an F# quotation to a JavaScript string, or prints errors to stderr and returns None on failure.

Learning F# with my 11 year old nephew, he is loving it, swapping out assets and creating new ones, adjusting gravity to what feels right to him and putting in very basic collision detection. Going to keep expanding on it over the year.

Flappy bird clone script using Mono's Xwt toolkit, click the mouse or hit space to flap, no collision detection. To run you will need to build xwt from source https://github.com/mono/xwt

Factorial with bigint and reduce

The .. operator that is used to generate ranges in F# core is quite slow. This snippet shows an alternative implementation that is about 5 times faster.

My Game in F#, creates the five times table up to 100 and then selects a random number from it. You then guess the number

Created during the morning session of Progressive.Net 2015 with Phil Trelford

Flappy bird clone script using MonoGame, click the mouse or hit space to flap, no collision detection.

Flappy bird clone script using WPF, click the mouse or hit space to flap, no collision detection.

Flappy bird clone script using WinForms, click the mouse or hit space to flap, no collision detection.

evReact is a library for recognition of events sequences. This snippet shows how to handle drag&drop in WinForms to drag a square into a bigger one without controls.

Inverse Gamma function and Inverse Factorial by Approximation based on these references: http://mathforum.org/kb/message.jspa?messageID=342551&tstart=0 https://github.com/DarkoVeberic/LambertW

One script to create MS-SQL-database and host OWIN Web-server with SignalR-clients

The F# Core library offers async.TryFinally which where a synchronous compensation function (of type unit -> unit) is run after an error or cancellation. However, it offers no way to start an asynchronous compensation. The TryFinallyAsync method defined below offers a way around this.

Set creation can be quite slow for large sets (> 15000ish string items). If input sequence to create the set is sorted then some optimizations can be applied. For even larger unordered sets (> 30000ish string items) it can be faster doing an up front sort on the data, and then using the Set creation method as described. 1) Set.union is very fast when the greatest element in one of the sets is less than the smallest element in the other; basically becoming an O(1) operation. And Set.add is faster for smaller sets than larger sets, given O(log2 n) of the add operation. So when we have ordered data, makings lots of smaller sets from the stream and union-ing them together can provide a performance boost. 2) On top of the method described in (1), because all the sets are immutable inputs and outputs, then they can be partitioned off onto Tasks to perform the set creation in parallel. If you are using Newtonsoft's Json.net, then provided is a JsonConverter that can be added to the serializer to use this for Set creation like: serializer.Converters.Add Newtonsoft.fastFSharpSetConverter

One of the problems from https://ocaml.org/learn/tutorials/99problems.html

Defines a "guard" function for railway-style error handing which allows you to concisely verify a condition when handling errors using Choice<'T, 'Error>. It checks the condition and if it is false, returns Choice2Of2 with the specified error value. If the condition is true then it returns Choice1Of2 (). Loosely inspired by Swift 2.0's guard keyword.

Go and Swift have a dedicated defer keyword which allows the programmer to specify code which should run when leaving the current scope, irrespective of errors. F# supports a similar pattern with IDisposable and the use keyword, but this requires either defining a class definition or object expression and the extra syntax can make the code less expressive. This snippet defines a simple helper function called "defer" to remedy the situation.

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.

One of the 99 OCaml problems rewritten in F#

f# has Seq.length but we ask that you reimplement it. Bonus for a tail recursive solution.

Find the k'th element of a list. (easy)

Find the last but one (last and penultimate) elements of a list. (easy)

Write a function last : 'a list -> 'a option that returns the last element of a list.

Backoff/retry with injected mapping from call result to success criterion, and backoff times as a parameter. (New version with the backoff in the right place!)

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.

changed x and z dimensions

just a test of fun3d

https://twitter.com/kot_2010/status/607115335255392256

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

F# computation expressions do not allow monadic expressions inside `finally` clauses. If we allow ourselves a bit of ugliness this can be circumvented by using a combinator. Here's an implementation for asynchronous workflows and a small application.

Functional programming operators related to the BCL ImmutableDictionary type.

Given a list of lists, the function crossJoin outputs all combination of elements from the inner lists, i.e. each combination is a list which contains elements from each of the inner lists in the input. Note: Order is not preserved

Trigroup

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

Sample code snippet to group the data into buckets

Rotate List

Compress List

R functions often return a list of results, indexed by names. This is a helper function which allows directly accessing the results using their names.

Replace elements

This is a simple four function calculator using FParsec. It would be easy to replace the FParsec combinators with simple parsing combinators to produce the same results, but without the nice error messages produced by FParsec.

Flatten Nested Type

c.f. http://fssnip.net/qR In this example different syntactic structures result in different types.

A long overdue counterexample of a pure bind/return computation expression that does not satisfy any of the monad laws, as promised to @silverSpoon. This uses binary trees under the hood, which define a binary operation but do not satisfy any unit or associativity laws. Binary trees can also encode the syntactic structure of a computation expression, which is being captured using a state-updating bind implementation.

Palindrome test.

No nulls FsCheck

castle

a

Utility module to more naturally use mutable Dictionary type from Collections library

Tripwire is a special part of motion detection that can be used to monitor and alert on specific changes. More specifically: tripwire means the detection of intrusion. This code snippet presents how to create a C# software by using prewritten computer vision components (http://www.camera-sdk.com/) allowing you to get notified when your USB webcam triggers an intrusion. For instance, by using this application, you can use your camera to alarm when a people enters into the shop/office, or even to count how many people entered, etc. After the necessary using lines and objects you need to implement the Main method and the necessary functions for connecting to a USB webcamera. The startBt_Click method is used to start the tripwire functionality. Thereafter you can see how to handle the enter and exit events. Nothing could be more simple! :)

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

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

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

F# Snippet based on Dave Crook's article "Intro to C# and Analyzing Government Data"; http://blogs.msdn.com/b/dave_crooks_dev_blog/archive/2015/04/20/intro-to-c-and-analyzing-government-data.aspx

A simple script that automatically recompiles LaTeX documents when they are saved. Works nicely when editing papers in Atom and using SumatraPDF for preview (Sumatra automatically reloads PDF documents). Does not report errors or anything clever (!)

Cache a function's asynchronously-computed result for each argument to reduce expensive and repetitive computation of an asynchronous operation. Uses a concurrent dictionary for backing storage, and at-least-once invocation semantics per key.

A conference call is a meeting, conducted over the phone using audio, between two or more people and usually for the purposes of discussing a particular topic. In my former snippets I dealt with text-to-speech and speech-to-text functionalities. So the implementation of conference calling can sound a little bit strange as compared with my previous tutorials. But I thought it provides a good opportunity for a new challange, so I thought I share my upshot expectedly that it will be useful for you. A softphone with built-in conference call feature can be greatly used in business communication as well as in companionship. The source code below is ready for use, so you only need to copy&paste it to your Visual Studio, then modify the necessary fields. (Do not forget to add the necessary DLL file providing the VoIP background to your references: http://www.voip-sip-sdk.com) This program will be a console application that functions as a softphone making conference calling possible. This solution assumes that you have a PBX with some SIP extensions installed previously. After creating the necessary using lines and objects, you need to define your PBX and provide the appropriate SIP account details in order to be able to register your application to the phone system. When you have created all the required methods for SIP calling, you need to initialize the conference room and handle the related events. AddToConference is used to add new party to the conference room and RemoveFromConference is used when the call is ended. Have a good time!

creates folder and file structure on the file system based on a tree output. Given a file generated from tree /f /a > file.txt it creates the structure on a given folder

Shows empty list constructor

sequence fibbonaci

FizzBuzz using Active Patterns.

"let rec inline" doesn't always behave as expected

Parsing cron expression and calculating next launch time from schedule. v 1.1: bugs fixed for case */n + catch bad parsings

Game evolution

Game evolution

Prototype of a CIL code optimizer that generates optimal code for bitwise functions. Update: General improvements

Playing with Chiron for JSON storage.

test

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

This is just the ML code from http://jozefg.bitbucket.org/posts/2015-02-28-type-inference.html ported to F#.

Normalisation of "F# quotations" by evaluation.

Formatting a Timespan to something fully descriptive and user friendly.

Overrides the standard Web API ApiControllerActionInvoker with one that works with controller actions return F# Async<'T> results.

Counting 1-bits in a DWORD (int32) using the 'divide and conquer' strategy

Turn a project based nuspec into a project type paket template (see http://fsprojects.github.io/Paket/template-files.html )

Getting started with Akka.NET

Simple retail domain for Tesco with scan, cancel and tendering and calculation of total price.

Extract images from all resources's ressources of all assmeblies in a folder

Attempt to reproduce caseInsensitiveString from http://stackoverflow.com/a/12938883/17049

See also https://fslang.uservoice.com/forums/245727-f-language/suggestions/6536829-implement-ocaml-s-new-match-exception-syntax

Generate timebased one time passwords, for use with tools like google authenticator, etc.

This example shows an implementation a MailboxProcessor<'T> extension method for posting messages and awaiting an asynchronous reply from a mailbox processor agent which mail fail. The error continuation is called if a failure event is triggered on the agent after the message is posted. The agent goes into a failed state where the result of all future messages posted with this mechanism is failure.

We sometimes come across business processes where it's important to respond within a particular time window. Here's an experiment modelling that with Hopac

How to print a formatted calendar to the console using F#

Hello Guys, This short ASP.NET code snippet is intended to provide you a brief review on how to add SMS functionality to your website. You will see, this is a very simple but smart solution. This ASP.NET application is able to send messages by using HTTP requests towards the SMS gateway that sends the SMSs to the destination telephone via a GSM modem or an IP SMS connection. Let’s take a quick look at the software requirements that are essentially needed for tjis solution. In order to send SMS messages from your ASP.NET application, you need a development platform, e.b Visual Studio, of course, .NET Framework 4.0, Internet Information Services (IIS) and an SMS gateway (I used Ozeki NG – http://www.ozekisms.com). You also need a GSM modem attached to your PC or an IP SMS connection to be able to send messages. Okay and now let’s use the code snippet! Copy the content of smssend.aspx and smssend.aspx.cs into the main directory of the IIS server - C:\\Inetpub\\wwwroot\\ directory (). Configure the fixed data in the smssend.aspx.cs file (the IP address and port number of the SMS gateway, username, password). Launch your SMS gateway Server. Start a web browser and enter this URL: http://127.0.0.1/smssend.aspx - where 127.0.0.1 means that the smssend.aspx and smssend.aspx.cs files can be found on the same computer on which the browser has been opened). Fill in the required fields, and then click the Send button. It’s as easy as that! Happy coding! :)

Async extensions for Socket. This extensions use SocketAsyncEventArgs, not Begin / End pattern.

Taken from FSharpx.

Trying to set a string option

Extended from: http://www.fssnip.net/d2

A Simple port of the Calculator BDD sample from http://cukes.info. Most BDD frameworks require attributes and shared state to run a test (I'm looking at you specflow!) As the test suite grows, the accidental complexity of different steps initialising (or not) class state becomes a huge problem, resulting in fragile tests. By accumulating state until the assertion, the tests become strongly typed and resilient to change. F#'s backtick methods combined with continuations and lightweight syntax can be taken to extremes to produce a lightweight internal DSL, with efficient results.

I came looking for a fast implementation of Perlin Noise, but the only code snippet showed value noise, which has discontinuity in its 2nd derivative. This version of Perlin Noise has 3 improvements over the default. 1. 1024 gradient vectors 2. Higher order smoothing polynomial 3. A better hash function This implementation has a slight change for performance reasons, and that is the removal of clamping the smoothing polynomial from 0.0 to 1.0, and no clamp on the final value, which would be from -1.0 to 1.0. I have not experienced any issues as in my code I have offset the values by scaling them into the range of 0.0 -> 1.0. I have tested this and profiled this code for many hours in order get the absolute best performance I could. This code runs much faster in release mode than it does under debug mode. I have profiled in both debug and release modes, and against Heikki Törmälä's SimplexNoise, and in release mode my gradient noise implementation is a lot faster and since it uses doubles the numerical limit is far greater, as the Simplex Noise function fails once the 32bit floats overflow. Keep in mind, this is 2D gradient noise, and I have not tested a 3D version.

This is a simple code implementation to copy Streams leveraging the Async workflow. After the first read, the write and read processes are done in parallel. I also used an Array of Array as buffer to avoid false sharing memory. An other improvment option could be to increase the buffer size if the copy is done in same machine.

A type-level SAT solver in F#, inspired by https://gist.github.com/wouter-swierstra/0b6062c9660e751cd535

Continuing from https://twitter.com/JKPappas/status/558339587719045120, here's an approach on extending units of measure to arbitrary types.

Functions to select the first element in an array that passes some predicate, and separately all the other array elements. (I'm not sure if this type of operation has a standard name. Please tweet me if you know!)

A function that will take a sequence of directory names and recursively find and return a sequence of all file names within.

You can create a 3D effect by taking each pixel from the source image (removing the red) and the pixel twenty places to its left (removing the blue and green) and blending the two together

This simple snippet shuffles the elements of a list. It can be useful for simulations.

Querying NuGet package manager via OData TypeProvider

Idea from Guy L. Steele - Organizing Functional Code for Parallel Execution; or, foldl and foldr Considered Slightly Harmful - https://vimeo.com/6624203

Adding together Option types

XTract (https://github.com/TahaHachana/XTract) is a simple screen scraping package for F#. This sample shows how to describe the data model using a record, define the extractors that will collect the data using CSS selectors, scrape the data from the target URL(s) and save it.

Turtle interpreter example using Mono's Gtk# library with example paths for MonoDevelop (running on Linux) and Xamarin Studio (running on Mac and Windows).

This is "Parallel tree processing" example from http://tryjoinads.org/ ported straitforwardly to Hopac.

https://github.com/tpetricek/FSharp.Joinads/blob/master/src/Joins/Samples.fs#L60 ported to Hopac.

An extension of MailboxProcessor that catches all unhandled exceptions, and ensures that the user-provided function is run repeatedly until it returns normally. Based on the HandlingMailbox defined by Tomas Petricek: fssnip.net/cj

Joinads example from here https://github.com/tpetricek/FSharp.Joinads/blob/master/README.markdown translated to Hopac. No language extension needed, the code is equally compact and arguably more readable.

One of the main features of Hopac - selective synchronization using "alternatives". In this snippet we download three web pages in parallel and the one that finishes first "wins" (or the timeout alternative becomes available for picking). What's nice in this solution is that the other two downloading jobs are cancelled immediately when the winner/timeout is available (i.e. an implicitly provided to the Asyncs CancellationTokens are cancelled). Alts is highly composable and, for example, the whole Alt.choose [ ... ] thing could be nested in another Alt.choose or combined with <|> or <&> operators with another Alt and so on.

This is a simple and direct implementation of fourth order runge-kutta ordinary differential equation solver algorithm. In the main function three use cases are shown.

With the usual Western music it is common to use the Equal temperament: http://en.wikipedia.org/wiki/Equal_temperament http://hyperphysics.phy-astr.gsu.edu/hbase/music/et.html Then the note frequencies are calculated by this formula. For more information: http://en.wikipedia.org/wiki/Pitch_(music) http://en.wikipedia.org/wiki/Musical_tuning#Tuning_systems

Generates a sequence of dates (ascending or descending), incrementing (or decrementing) by one day at a time, inclusive of the start and end dates. This is just simpler alternative version of: http://www.fssnip.net/oS (which was password-protected)

Minimal SNOBOL abstract syntax tree (AST), interpreter and internal DSL (but no parser), just enough to run some simple samples from Wikipedia's SNOBOL page: http://en.wikipedia.org/wiki/SNOBOL and most of the pattern matching examples from the SNOBOL 4 Tutorial http://www.snobol4.org/docs/burks/tutorial/ch4.htm

Microsoft Kinect Body Basics with Kinect SDK 2.0 and F-Sharp

Analyse word count from files. You can use it e.g. to create Tag Clouds

Generates a sequence of dates (ascending or descending), incrementing (or decrementing) by one day at a time, inclusive of the start and end dates.

Removes the nth element from a list

Based on Uncle Bob's State Machine Compiler for Clean Code video series, parser implemented with FParsec, see https://github.com/unclebob/CC_SMC for Uncle Bob's Java implementation.

Based on Uncle Bob's State Machine Compiler for Clean Code video series, parser implemented with FParsec, see https://github.com/unclebob/CC_SMC for the Java implementation.

Works by forcing yourself to close Outlook and then notifies you an hour later.

graham scan algorithm for finding the convex hull of a set of 2-dimensional points

построение дерева решений

построение дерева решений

Playing with simplified domain modules and event sourcing in F#

Casts list of objects to any other type. Return objects if cast is possible, so new list can be shorter (or empty).

A more idiomatic definition of a Rational type with custom operators.

Transparent snowflake using polygons and rotational symmetry, based on paper and scissors method.

Script to render a Koch snowflake using a Windows Forms bitmap.

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

Naive performance comparison of push model libraries: Reactive Extension (Rx), Observable module (built-in to F#) and Nessos Streams. Note: smaller numbers are better

This is a simple way to flat a two dimensional array in a linear one

Solves the "Two Logicians" puzzle.

Generates strings that are similar to the input, as measured by the probability of a symbol depending on preceding symbols. (Markov chain) The order, which defines how many preceding symbols to look at before placing another, is variable.

Lock-free, mutable list that supports multi-threading scenarios.

A work-in-progress implementation of Lambda Calculus - Alpha and Beta reduction is buggy

An example of the composite pattern implemented simply with functions and object expressions

A simple example of a decorator pattern using object expressions and the pipeline operator for a fluent interface

Simple example of Eto library usage for drawing

Reversing RELEASE_NOTES.md Very ugly version hacked together in a minute

An example of using an actor (MailboxProcessor) to coordinate the projection of events from an event stream into a persisted projection. This example covers handling simple concurrency conflicts via also persisting and checking the latest event ID with with projection. The update command will take the current projection and apply all new events before persisting it back. The rebuild command will ignore an existing projection and replay all events in the stream.

test of Async.StartWithContinuations

Find what's been added, removed or changed between two lists (perfom a diff between two lists of items).

Type extensions for ASCII strings represented as byte arrays. Note: requires the F# 3.1 compiler.

There are better (faster, more efficient) ways to do this, F# numerics library for a start, but this is at least interesting. This snippet uses the polar form of the Box-Muller method to generate Normal- (Gaussian-) distributed random numbers as an infinite sequence. The polar form is more efficient than the basic form as it does not rely on trigonometric function calls, but there are far more efficient alogrithms (read harder to implement) e.g. the Ziggurat method (for a later post).

Single Case Active Patterns

Less-nonsense 8-line retry function that will retry a function a specified up to `maxRetries` times while it throws. After the retries, any remaining exception is allowed to propagate. Accepts a before function to allow you to wait/report when a retry is taking place

Suggestion for a core library function.

The snippet implements a simple agent that limits the number of parallelism. When created, the agent takes the maximum number of tasks it can run in parallel. When it receives a "Start" message, it will then either run the task, or store it in a queue until earlier task ha completed.

This is a basic parser that I wrote which takes heavily from the examples in Dom Syme's Expert F# book and http://fsharpforfunandprofit.com/posts/pattern-matching-command-line/

It's probably not possible, but I'm going to see how far I can get...

Using Azure Table Storage with WindowsAzure.Storage

Agent demo

Async demo...

Demonstration Hall Paradox Game1 xxx - 1 strategy; Game2 xxx - 2 strategy (change choice).

Minimal Logo implementation using FParsec with support for procedures.

Backtracking search for Constraint Satisfaction Problems (CSP)

A quick NodaTime.Instant generator for FsCheck

Extension for Async module: channel for transmitting data between subsystems, launching parallel groups of asyncs sequentially.

Make the (!) operator even more useful by duck typing it. Simple and effective!

This script finds all possible divisors of a number

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.

Test Anything Protocol runner for NUnit lets you run unit tests within an F# interactive session.

Extension to Control.Observable module to create an Observable linked to a MailboxProcessor. Messages posted to the mailbox are published to subscribers. Requires a cancelation token which when cancelled sends OnComplete to subscribers. Only the Post method is exposed from the internally created MailboxProcessor.

Somewhat implementation coupled, but the ideas are pretty neat. works in linqpad, not sure what's up with this editor

There are some nuances to using the regular expression type provider that are easy to miss. This snippet addresses them.

Needed to partition a list into multiple groups, but couldn't find an existing way to do it. Have not put this as an extension method as needed it in an .fsx file which is loaded, but couldn't get extension method to work from that.

263 bytes (unix line endings ;))

Small F# snippet on how to read 32-bit integers from a file at specific indexes.

Simple function for commute binomial probabilities. For quick summary about binomial distribution: 1.) There are a fixed number of trials (n). 2.) Each trial has two possible outcomes: success of failure 3.) The probability of success (p) is the same for each trial. 4.) The trials are independent, meaning the outcome of one trial doesn't influence that of any other.

Split a list into chunks using the specified separator. This takes a list and returns a list of lists (chunks) that represent individual groups, separated by the given separator 'v'

Simple Cost Study

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

A fun little trick.

Forgotten file for F# Works |> Paris!!!

following http://vimeo.com/groups/97577/videos/97315970 to make my own html DSL

An extra primitive that can be used to safely unbox to Some<T>. Useful for use with options where only a single type match is needed and a function is only applied if successful.

@Samuel - saw your post and thought one part was similar to bit shifting I was playing with yesterday, so rewrote the FromBooleans function using a fold instead of ref cells. Probably not as readable as your version though :)

Convert an array of booleans to an array of bytes with 8 booleans packed in one byte. The reverse operation from a byte array to a boolean array is also provided.

Full source code for my blog entry on this subject - http://chrsb.co/BNqAbM

single-case DU with shadowed constructor for passing non-primitives around that are already validated.

Whilst working on a google API wrapper, I came across the need to separate a sequence into sub-sequences based on a separator condition. This also led to a requirement for versions of takeWhile and skipWhile which also include the element which first breaks the condition predicate.

Try get a value from a dictionary and return a default value when not found. I provided two version. Pick the one you like the most.

Zip file type provider

Creates a map containing each item and its frequency as a key/value pair. Then sort by value in reverse order before printing each item.

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

Plays the perfect game of Tic-Tac-Toe using the Negamax algorithm.

How to generate functions for copying F# record-array-union trees with Expr.

Function that converts a base 10 number into a base 26 (digits from the English alphabet) one. A=1, B=2, ..., Z=0

One of Jenkin's hash functions

Memoize from _real world functional programming_ by Petricek and Skeet chapter 10 tutorial

Using Type Provider generated functions for type safe logging.

Word guessing game using ASCII art.

Smallest divisible number between 1 to any number.

Just a quick and dirty hack

Different ways to write lazy values - using the lazy keyword or the Lazy.Create function. Pick the one you like the most!

A variation of another snippet "Seq.groupWhen". This one groups adjacent elements based on a predicate that accepts two arguments - the previous and current elements

A script suitable for FSI that copies a (UTF-8) text file throwing away uninteresting lines in the process.

An F# bigint range is slow (see SOQ: http://stackoverflow.com/q/20534191). This an IENum built specifically for bigint that has reasonable speed. ~4 seconds instead of nearly 20 on my old mac mini

A few short usage examples for the FSharp.Date Type Provider (available on Nuget).

Just something I whipped up to check out the Marvel Comics API using JSON Type Provider

Convenience function to easily throw an argument exception with a helpful string description. Looks simple, but was hard to figure out.

Generating a state space tree to the Missionaries and Cannibals Problem (http://en.wikipedia.org/wiki/Missionaries_and_cannibals_problem). Then, this tree is iterated with depth-first approach, printing all the visitations. The solutions to problem have a depth equals 9.

XmlSchemas are used to validate XML documents. Following demonstrates how to infer a schema from sample documents. They are also used to visualize the structure of a class of documents.

Simple implementation of the popular game "2048". Can you add up the tiles and reach 2048? The game can be played in fsi or you can add the GUI which is so far missing.

A generic numeral G. It allows writing functions for arbitrary numeric type. The transformation is an efficient one, because it is implemented explicitly for every type. It combines the type classes technique of FsControl (https://github.com/gmpl/FsControl and http://www.nut-cracker.com.ar/index.php/typeclasses-for-fsharp) with numeric literals. But FsControl is removed to completely avoid unnecessary function calls.

Check string of palindroms

Prints a list in a spiral

Shuffling array using Seq.fold

Demonstrates a possible encoding for GADTs in F#. It is type safe, uses no reflection and pattern matches can be declared outside of the definition itself. See also http://lambda-the-ultimate.org/node/1134

Demonstrates a possible encoding for GADTs in F#. It is type safe, uses no reflection and pattern matches can be declared outside of the GADT definition itself.

Knocked together a bare-minimum TCP wrapper for MailboxProcessor. Not intended for production.

Small quiz-game with World Bank TypeProvider (from FSharp.Data Nuget-package): Which country has the capital city of (random capital)? (Three options)

For tutorial, example how to use option type.

For tutorial, the same functionality, different styles of pattern matching.

Helper modules for different kinds of memoize functions.

A different way of expressing private DU constructors.

I read all the suggestions on http://fslang.uservoice.com/ . They are great suggestions! I found some of then are realized well by using current language features. Then I introduce them.

Actor implementation (much simplified) intended for use on mobile devices. Seems to provide better memory usage behavior than native F# Mailbox Processors (MPB) (on Android). Though is not as 'smooth' as native F# MBP. Smoothness here refers to how processing is balanced between consumers and producers (most relevant to single core machines).

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.

Generate random hex-string and calculate base58encode. I made these for some initial BTC-testing, but didn't test too much... seems to work, but would need some unit-tests... :-) Feel free to update or add new versions.

"a binary numeral system where two successive values differ in only one bit" http://en.wikipedia.org/wiki/Gray_code http://FunctionalSoftware.net/starten-mit-f/

This snippet shows how to transform simple recursive factorial function to combinator form step-by-step.

Tired of confusing dictionary instances with different comparers (I am)? Stick it in the type, à la ocaml-core maps.

A simple function that creates a counter function (with localized mutable state).

If you have a dynamic IP adddress for your computer on the internet and need your host name to resolve to that address you may use a service like DynDNS.org. This program will check to see if the host name resolves to the same IP address currently assigned to your computer. Works behind a router with NAT.

This time with recursive function through computation expression around continuations...

A simple computational expression to deal with asynchronous calls that return a choice type to signal failure. Useful for calling remote services that may fail - you can call the remote service with functions of type "request -> Async<Choice<'success, 'fail>>" and then chain the results together.

This is a Pigeon/Akka actor based on pure (if you remove printf) function instead of inheriting from a class..

Type provider for acceess more datafile via class property.

One solution to Rosalind rabbits problem.

Await a wait handle with a cancellation token and optional timeout. Returns a flag indicating whether the handle was signalled, the timeout period elapsed, or the wait was cancelled.

Generates simple systems of linear equations, suitable for being solved by someone who's just started learning about them. Change the ranges to make them suitable for solving without a calculator.

Recently witnessed a C# programmer struggle with the fizz buzz interview question. But it is straightforward in F# using pattern matching on the two-factor decision table.

Compute MD5 hash of a string

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'

After watching this clip (http://www.youtube.com/watch?v=ZhuHCtR3xq8) on Youtube featuring Brian Beckman I wanted to try to sketch Brian's main argument that Monads' main purpose is function composition. I will post my sketch to http://rodhern.wordpress.com/2014/02/ . These snippets are the companion examples to the blog post.

I needed a crude k-means (http://en.wikipedia.org/wiki/K-means_clustering) clustering method for a one off test of something, and decided to try to do in F# for learning purposes

calcula la matriz inversa

Example active pattern for tweet.

Simple version of the azimuthal equidistant projection (see also http://fssnip.net/lA) but with measures. This avoids mixing of degrees and radians and longitudes/x and latitudes/y

After watching this clip (http://www.youtube.com/watch?v=ZhuHCtR3xq8) on Youtube featuring Brian Beckman I wanted to try to sketch Brian's main argument that Monads' main purpose is function composition. I will post my sketch to http://rodhern.wordpress.com/2014/02/ . These snippets are the companion examples to the blog post.

After watching this clip (http://www.youtube.com/watch?v=ZhuHCtR3xq8) on Youtube featuring Brian Beckman I wanted to try to sketch Brian's main argument that Monads' main purpose is function composition. I will post my sketch to http://rodhern.wordpress.com/2014/02/ . These snippets are the companion examples to the blog post.

Simple and a more optimized implementation of the azimuthal equidistant projection. Input is expected in degrees.

This is the getting started sample for the numl machine learning library available at http://numl.net/ written in F#.

Similar to the snippet by Kit Eason, but using Net Office. Also handles large spreadsheets, but with some compromises, e.g. using Array2D rather than Seq and not supporting filter. To use, paste code into VS, open Excel (as the code works on the default workbook loaded) and then use FSI.

Parse INI file (hi old school :) ) via type providers. WARNING: add to project ProvidedTypes-0.2.fs & ProvidedTypes-0.2.fsi from http://fsharp3sample.codeplex.com/SourceControl/latest#SampleProviders/Shared/ProvidedTypes-0.2.fs

brute force pattern building for an array tail

Match the first elements of an array an returns tail.

Discussion here http://stackoverflow.com/a/21434034/801189

F# version of the code samples from an article "Fun with infinite sums" by Phil Haack. Using infinite sequences to separate the concerns and F# charting for simpler visualization.

Write graph as dgml file

Solution to the layout binary tree problem from 99 OCaml problems

This is a pattern I knocked together to address the issue of global mutable state in the F# compiler.

Using task based async, won't block the thread.

String.notNullOrEmpty extension to strings

Learn Key Principle of F# in just a few minutes with the following Sample of "World Bank Type Provider - Exploring Population Data"

Verifies the OAuth SWT (simple web token) issued by Azure ACS The SWT may be obtained by many methods; one way is: - "How to: Request a Token from ACS via the OAuth WRAP Protocol" (http://msdn.microsoft.com/en-us/library/windowsazure/hh674475.aspx) (Note I used the userid/password method to obtain the token on behalf of a 'service identity' set up in ACS) The token is normally verifed by a 'relying party' such as an ASP.Net website hosting a Web API General ACS documentation is here: http://msdn.microsoft.com/en-us/library/gg429788.aspx

If you have read the awesome book by Jeffrey Richter CLR via C# 4 ed. you have discovered that there are more optimal ways for thread synchronization than the one provided by the BCL. One of them is the use of new asynchronous capabilities in order to create an asynchronous synchronization primitive. In the book it is presented an AsyncOneManyLock which is used for thread synchornization for code with a high demand for responsiveness and scalability. If you are an F# developer you know that the F# Asynchornous Workflow and the Task Parallel Library are different, so I decided to port this useful piece of code to F# and show you how to use it with an example.

Perform parallel Async returning heterogeneous types. (The solution presented here is based on a gist sent to me by [Anton Tayanovskyy](http://t0yv0.blogspot.com/ "Anton Tayanovskyy"), Twitter: [@t0yv0](https://twitter.com/t0yv0).)

.Net exceptions carry with them lots of useful metadata that are not directly user modifiable. In certain applications, such as distributed or symbolic execution it might be reasonable to need to modify such metadata. The following pattern is a proposal on effectively decoupling an exception from its contextual metadata, as well as a way of defining exception hierarchies while avoiding all the ISerializable boilerplate.

Simple prototype C# AST and parser using the FParsec parser combinator library. Parses a subset of C# 1.1 constructs.

Small Basic abstract syntax tree, parser and interpreter. Supports Small Basic's keywords and arithmetic, logical and comparison operators.

Get/put field/property and invoke method (one and multi arguments) via "?" operator.

Querying a players table grouped by first, then by the last name and counting the number of occurrence

A different, sketchy attempt at hexdump.

A more f#ish version of Robert's version http://fssnip.net/l9

Print a byte buffer in the same way unix tool hexdump would.

A fixed-size hash table of Maps. Adding and removing key-value pairs replaces one Map in the spine of the hash table. Threads can read from this collection concurrently while a single thread is writing into it. I created this as a response to the recent thread by Ayende Rahien about the performance of purely functional dictionaries. According to my measurements this collection is 3x slower to build and 2x slower to search than a thread-unsafe .NET Dictionary but it provides the thread safety he requires. However, the built-in .NET ConcurrentDictionary is slightly faster than this and provides stronger thread-safety guarantees.

Small Basic abstract syntax tree, interpreter and embedded DSL. Supports Small Basic's keywords and arithmetic, logical and comparison operators.

Useful if you are writing to the console from multiple threads and want to avoid goofed up text

Identify differences between two generally aligned strings.

Compiles simple F# quoted expressions (literals, values, operators, ifs and for loops) to Java code.

For example executable, install NPM and stylus package.

Factorial recursive function using match ... with pattern.

Factorial recursive function using match with pattern.

Tomas has released their F# data analysis library called Deedle, I just got around to playing with it. It looks really cool!

A simple implementation of the Douglas-Peuker path reduction algorithm. Use for simplifying curves, for instance in plotting coastlines. Loosely based on this implementation: http://karthaus.nl/rdp/

This is simple implementation of interval and fuzzy calculus.

Sample retail domain model, using F# types (records and discriminated unions) with JSON sample data using F# Data type provider.

Function to Convert a float to a mixed number. My thanks to John Kennedy of Santa Monica College for his "Algorithm to Convert a Decimal to a Fraction" (see link).

High performance asynchronous Logging module with time-based rollover and size-based file retention in under a 100 lines of F#

Demonstration of the manyproc sample from Erlang using F# MailboxProcessor.

Supervised learning algorithms need a training set and a test set. This snippet show two ways to generate train/test sets. First is by count, where it will take a random number of rows from the Frame and generate two new frame of the specified size. This is useful if you have a very large dataset, but you only want to explore your learning algorithm on a small subset. Second is by ratio, this will break the frame into two parts based on the ratio given. For example you might want to train on 25% of your data, then test on the other 75%.

Convert a BitArray to a sequence.

An implementation of a minimum spanning tree calculation algorithm based on Kruskal's algorithm

Lazily generate fizzbuzz results and provide a test function. Parameterize the inputs and predicates.

Selection of helper functions for generating test data.

A quick and dirty function to check to see if there are files present in a directory. Note this will return false if there are only subdirs in a directory.

When printing None via printfn (or any of the other print functions for that matter), the result is <null>. This example shows why.

bank OCR code parse from London's ProgF# 2013

Huffman coding in F#. frenchCode courtesy of M.Odersky.

Actors with control actor. No mutable state.

Simple, but slow. Don't do this at home :)

From progfsharp tutorials

User Story 1 at http://codingdojo.org/cgi-bin/wiki.pl?KataBankOCR 1. Define a function which retrieves text of a single digit with specified index in text of a number. 2. Make a sequence of texts of each digit of account number. 3. Find indices of text of 0 to 9 digit which satisfies structural equality to them.

SkillsMatter 2013 F# Tutorials Programming with the Stars Code Snippet

See: http://codingdojo.org/cgi-bin/wiki.pl?KataBankOCR Prog. F# 2013 - London

User Story 1 from the Bank OCR Kata: http://codingdojo.org/cgi-bin/wiki.pl?KataBankOCR

Function to combine the values of a list of sequences into a sequence of lists where each list contains the nth element of the different sequences. It works like zip but for an arbitrary number of sequences and it returns lists instead of tuples. As with zip when one sequence is exhausted any remaining elements in the other sequences are ignored.

Log file parser for log4Net files

See: https://github.com/fsharp/FAKE/issues/171 This is a parser for RELEASE_NOTES.md files for F# projects. Handles both simple and more complex file formats described in the link above.

With love to Ilker...

Filter by list of properties when provider supports filter expressions but doesn't support Contains. Equivalent C# : https://gist.github.com/mausch/6893533

An F# wrapper for HtmlAgilityPack

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.

Here's a very short, very simple, example for Algebraic Manipulation of the equation x + y = z

xBehave Quickstart sample conversion in F# using a custom operator: https://github.com/xbehave/xbehave.net/wiki/Quickstart https://github.com/xbehave/xbehave.net/wiki/Scenarios-with-examples

xBehave QuickStart sample conversion to F# from C# with some helper functions: https://github.com/xbehave/xbehave.net/wiki/Quickstart

xBehave QuickStart sample direct conversion to F# from C#: https://github.com/xbehave/xbehave.net/wiki/Quickstart

I think the following function is useful allowing you to do an Option.map + defaultArg in one go (plus defaultArg argument order is a little annoying). Might need a better name.

Small script to generate a X509 certificate for testing purposes. In my case, for generating signed PDF documents. This will write the certificate and it's key out into a Pkcs 12 store. It relies on the BouncyCastle library (version 1.7 worked fine).

Uses dynamic operator to quickly create XML

Testing

Lori's calling module

Test

Strangely enough, really useful documentation of F#'s "function" keyword used for pattern matching is difficult to find within Microsoft's official documentation. A Google search turns up some helpful illustrations and discussions of the keyword. Here's a simple example that some might find useful.

Lori's module

Fold a string with one delimiter except for the last with a different delim. So basically if you have a list ["1";"2";"3"] and you want it to be ["1";",";"2";"and";"3]

Purges files in bin and obj folders, useful to reduce size when copying project folders. Be careful, this script will delete files!

The snippet shows how to define the "=>" operator in F# so that it can be used for creating named parameters for dynamic API.

Playing with the OO Strategy Pattern and the F# type system

Observer Pattern

Factory Pattern

Decorator Pattern

Implementing the strategy pattern by putting all the strategies as a static member function for a class that can't be instantiated like the singleton

Partial wrapper for Amazon S3 for both the Web and SOAP APIs. Generates signatures for both APIs (which was the tricky part). Uses WSDL Type Provider for SOAP. Uses SOAP for bucket list and delete operations and WebAPI to upload/download object contents (streamed / async)

Splits array into chunks, returning seq of seqs. Works with F# 3.x

Implements a technique found in http://stackoverflow.com/a/2085377. Useful for rethrowing exceptions in the context of computation expressions, not otherwise possible, as well as a few other applications.

I needed a function to generate a tree from a c# class that had some odd semantics, but when I refactored it, I realised almost everyone must have something similar knocking around their codebase, so here's mine.

test

Converts an excel column identifier like "AR" to a zero-index number

Blow up words to ASCII art with this 5x5 font

WPF version of Missile Command. Run as a script in Visual Studio or create a new application project, reference the assemblies listed at the top of the script and paste the code over Program.fs and hit F5.

Click on the tsunami.io button below to launch the online tsunami.io IDE with this snippet. Then select all the code (CTRL+A) and hit the Run button to start the game window, then just dock the window to the right of the code.. Click in the game window to launch missiles and save your cities.

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.

A simple trick for defining positive infinity semantics.

See http://stackoverflow.com/questions/18595597/is-using-a-stringbuilder-a-right-thing-to-do-in-f

Continuing from Nick Palladinos' session types, this snippet is an implementation of indexed monads in F#, as well as a collection of examples that demonstrate its utility: session types, type-safe serialization and reversible workflows.

Convert negative and positive integers to a positive value by using an overlap and interleave scheme (more info: http://en.wikipedia.org/wiki/Golomb_coding).

This snippet is a direct adaptation of Nick Palladinos' Session Types found in http://fssnip.net/j5. The implementation eschews the need for explicit declaration of duality objects by encoding all relevant information in the session signature itself.

A simple example that shows how to refactor discriminated unions to extract common members

Count the number of bits in a bigint (System.Numerics.BigInteger) and a BitArray. Note that version 4 is the fastest.

Binary Search Tree and Depth-First Traversal (PreOrder, InOrder, PostOrder)

If you have a directory containing multiple zip files, unzip them all in one pass. (Requires .NET 4.5)

A version of mapi for very long sequences that uses long integers instead of regular integers. I didn't use a mutable variable because of this http://stackoverflow.com/questions/1480582/the-mutable-variable-i-is-used-in-an-invalid-way

A minimalist XML Parser

Sequence expression which deals with cartesian product of sequences with for ... do expression. It replaces nested for .. do expression to single one.

Converts a byte list to a bit list. Takes a list of bytes and transforms it all into a flattened array of bits. For example, > bytesToBits [|byte(0x0F);byte(0xF0)|] 16 ;; val it : byte [] = [|0uy; 0uy; 0uy; 0uy; 1uy; 1uy; 1uy; 1uy; 1uy; 1uy; 1uy; 1uy; 0uy; 0uy; 0uy; 0uy|]

Calculate the great-circle distance between two points on a sphere. (Not done to one-up Samual Bosch's version, but coincidentally inspired by his previous DBSCAN post.)

Generate a random expression and evaluate it

Display message in f sharp.

Assign value to variable in functional programing language F #.

Cumulative bivariate normal distribution in F#. I implemented this using both the code given in Haug's complete guide to option pricing formulae book (which in turn credits his version to Graeme West who in term adapted code from Alan Genz) and using the code available on Alan Genz' website. This code requires the availability of another function called cnd which implements the (univariate) cumulative normal distribution. I haven't included my code there, since that's readily available in .NET from various sources (e.g. Math.NET, alglib, ...)

Compute the great circle distance of 2 points

Density-based spatial clustering of applications with noise (DBSCAN) is a data clustering algorithm. For more information see http://en.wikipedia.org/wiki/DBSCAN. The implementation is based on the pseudocode in the article and the following C# code http://www.c-sharpcorner.com/uploadfile/b942f9/implementing-the-dbscan-algorithm-using-C-Sharp/ The implementation is not very functional but does the job. Added pwd by ignorance, the password is "fssnip" (without quotes)

A function to display digit from ML coding Dojo by Mathais

The snippet defines a combinator 'tailrec' that can be used to express tail-recursive functions. If you use 'tailrec' and do not mark your function as recursive, then the function will be a tail-recursive one.

Algebraic effects and handlers is a new modular approach for handling effectful computations in functional languages. Inspired from the paper "Handlers in action"

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.

AsyncBuilder extension for maniplating some other containers directory in asynchronous workflow. Bind methods in the extension enables you to retrieve inner values of 'a IObservable and 'a IEvent by using let! or do! keyword without Async.AwaitEvent or AsyncAwaitObservable. For method in the extension omits let! binding. Yield method in the extension enables you to yield value in for expression in asynchronous workflow.

Had to throw together a Haskell-style Either type in F# since Choice is a pain in the ass.

Calculate the root-mean-square of a dataset. Eg. given the voltages over time of an alternating current, calculate the RMS voltage.

Bron–Kerbosch algorithm is an algorithm for finding maximal cliques in an undirected graph http://en.wikipedia.org/wiki/Bron%E2%80%93Kerbosch_algorithm

Untyped version of toml parser. The lines of code was reduced 173 to 45. It's based on some implementations in other languages (https://github.com/mojombo/toml#implementations). I was surprised that even a parser written in Objctive-c was simpler than mine (http://fssnip.net/jd). Then I read some others code and found that removing types which describes toml values simplifies the implementation. The code may seem little crazy, but I'm fine :)

F# introduction course - Get and read the Titanic data set using CSV type provider, define the type of "feature" and use it to classify the data and then implement a simple decision tree that can be used for writing more complex classifiers. To be used in Try F#.

Parser for Tom's Obvious, Minimal Language (https://github.com/mojombo/toml).

A F# crash course taught to Year 6 students (11 year olds).

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

F# introduction course - Getting data about cyclones from Freebase and plotting the dependency of damages in USD on the wind speed (with linear regression). To be used in Try F#.

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

Delimited continuations encoded as a parameterized continuation monad.

Knockout (http://knockoutjs.com) provides observable primitives similar to IObservable in Rx. Knockout also has ko.computed, which abstracts away individual subscriptions: you write a function that references the current values of observables, and it takes care of the rest. Here is ko.computed in F#.

An implementation of session types in F#. Inspired from the paper "Haskell Session Types with (Almost) No Class"

Placeholder syntax like scala or clojure. It can be used when the situation point-free style can't be applied. It only works for binary operators. But it's quite simple and can be used somewhat.

The simplest F# semicoroutines via seq. comprehensions http://en.wikipedia.org/wiki/Coroutine Replaced a custom function with the pipeline operator.

Generic higher-order function to measure timing of a given function

File parsing, based on multiple lines, using recursive pattern matching with many :: (cons) operator

This is a small example of invoking Win32 API. It gets the url which is opened by Google chrome's main window.

A bit more functional version of this: http://fssnip.net/iR

This module extracts all the <script src="blah.js"></script> blocks out of an html page's header. This can be useful if you are writing tools to merge all the js for future minifaction, or for otherwise manipulating the files.

A cool F# quine

Functional-style examples used during my talk for the Seattle F# Meetup on 7/17/2013 See corresponding imperative-style examples at http://fssnip.net/iO

Imperative-style examples used during my talk for the Seattle F# Meetup on 7/17/2013. See corresponding functional-style examples at http://fssnip.net/iP

Just occasionally, it's useful to be able to do the equivalent of System.IO.File.WriteAllLines, but without the line-ending on the final line.

Everyone else has a concat, so why not Option.

basically an extension of http://msdn.microsoft.com/en-us/magazine/gg983490.aspx I can't remember why I wrote it now, it should be more generic than MSDN's version.

String split function that skips quoted strings, useful as a simple CSV parser

Parsers a minimal expression tree allowing for functions of the form "func(arg1,arg2,...)->{body}"

This uses fparsec to parse locale files of hte form Id = text {arg:type} = newline = newlne For use with localization.

Even with the latest tools, we're sometimes exposed to .NET archeaology: parts of the framework designed before .NET 2. Examples of this are the dictionary classes from System.Collections, which are a little strongly typed, but not quite -- you see them if you call HttpUtility.ParseQueryString, or if you use pretty much anything in System.Configuration. Here's some code to make these classes a little safer in F#.

For a given integer year the snippet calculates the date of Easter. This is valid in the Gregorian calendar for years 1583 onwards. It is based on a method devised in 1876 which first appeared in Butcher's Ecclesiastical Calendar.

Useful for pinvoke stuff where your native API requires that you have a unmanaged buffer containing the data you want to work on. Edit: Changed native calls, removed Marshal.Copy (there is a async corner case but I won't delve into it here) and replaced with pinning.

Old School Way to Query Twitter API(Works in VS 2010, without a Type Provider). Ported from partially working C# snippets on another blog. Fully tested and working. Define your own string parmeters for OAuthToken OAuthConsumerKey OAuthTokenSecret OAuthConsumerSecret ScreenName to get this sample to work.

Generates a WAVE sound file

A simple retry combinator with customizable retry policies.

Query google.com (in english) without using any API key with the default WebClient class We are also instrumenting google ability to search between certain time period example: querygooglen 500 3000 "F#" 30 Here you fetch for 500 urls (we are grabbing 100 urls by query on google) wait between each query to google.com for 3 seconds you are seeking for the keyword "F#" you only want results who are at least newer than 30 days ago -Nicolas http://hackeratwork.com/

Simple symmetric key cryptogrphy. Ok for low security usages.

A simple Twitter search function, leveraging the JSON type provider.

Peeks from a few seq randomly according to specified frequencies. not tested

backup files , construct directory structure and then copy them one by one, ignore some sub directory in ignore list

Several ways of counting leading zeros in a binary number.

A simple yet powerful library for parallel collection processing. Inspired by Clojure's Reducers.

Trying to understand why some type inference used to work in OCaml and not anymore in F#

This code wraps System.Threading.Tasks.Task (that has no return value), properly, so that cancellations and exceptions are preserved, and exceptions keep their stack-traces. It is to be used when the Task only denotes a single computation or value, as it only picks the first exception from the list of exceptions.

Dear #fssnip newbies, please do not write F# code as if you are still in C#. Direct ports are meaningless. Among other things, please learn what structural equality is.

Tests if a string is a palindrome (whitespace independent)

This is a modification of the flood fill algorithm to find the largest contiguous block of items in a 2D array. Also includes a simple flood fill finder given a canvas and the target point

A simple module for registering option types with ServiceStack serializer.

Generates Text art in the style of Philippe Decrauzat's D.T.A.B.T.W.H.A.H.E. 2010 currently exhibited at the MoMA NYC

Cleaning up source code for a Forth like language before the compiling stage

Simple binary search of an array. Tests the array at the middle and divides the search space by half each time it looks for the target item. Returns the target item and how many iterations it took to get there

Iterate simple b-tree

Parsing simple formulas using active patterns

C++ style metaprogramming in F#

http://msdn.microsoft.com/en-us/library/vstudio/dd483467(v=vs.100).aspx

dump out saved windows wireless passwords in plaintext. they're stored in xml file, to successfully dump them you must be logged in as the same user who created them (at least in the below code ;)

So I disposed :(

A combinator that enables real imperative code in F#. Use with caution!

My take at Project Euler #4

An attempt at defining Peano arithmetic for all numeric types

A basic recursive implementation of merge sort on lists of ints.

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.

Shows how to generate a Gantt chart to visualize a schedule. Note: Requires BinPacking.fs found here: http://fssnip.net/hG

A simple implementation of a very basic command pattern that is being submitted to an Android app called GoF Design Patterns by Poash - highly recommended btw. This is imperative/oop in style, hope it helps someone. It is my first submission and I'm an F Sharp newbie!

Generic operator that introduces a convenient syntax for "posting" messages into any agent that has Post member. Specifically, it's useful for the standard MailboxProcessor and the AutoCancelAgent (from FSharpx library).

Higher order function

Implementation of the 'best fit' heuristic algorithm for bin packing problems. Incudes an implementation of 'binary tree with duplicates'. See this blog post for details: http://fwaris.wordpress.com/2013/04/01/best-fit-bin-packing/ Update: Bug fixes and added 'worst fit' heuristic implementation

A generalised version of the solution to the fourth Project Euler problem - Largest palindrome product, using sequences. The key to understanding this code is how "Seq.map (fun x -> (Seq.map (fun y -> x * y) baseSeq)) baseSeq" generates a sequence of sequences that contains the products of all possible combinations of two n-digit numbers. "Seq.map (fun x -> (Seq.map (fun y -> x * y) {1..3})) {1..3}" will generate: seq [seq [1; 2; 3]; seq [2; 4; 6]; seq [3; 6; 9]]

I have provided a class that implements adaptive boosting (AdaBoost) which is a very elegant technique to create a strong classifier from a set of weak classifiers. The strong classifier is the sign of the weighted average of the best N weak classifiers where N is a user specified parameter. The training process consists of N selection rounds. During each round, the training samples are given a weight distribution. The classifier selected is the one that has the least error which is equal to the weighted average of incorrectly classified samples. Training samples that have been incorrectly classified are given a larger weight for the next round. This increases the likelihood of drafting a weak classifier that can help with as yet misclassified samples.

Example on the use of Workflows in parser combinators.

Asynchronously perform a computation until it completes or timeout is reached.

Asynchronously await task completion with timeout support.

This snippet is an example of how to implement parser combinators in a simple way.

The snippet shows how to extend the built-in F# async computation builder with the ability to await standard .NET tasks using the let! keyword.

A simple function that nicely formats arrays of bytes. Useful in FSI or logging. byte array -> string seq Inspired by http://fssnip.net/hq, but optimized to become O(n).

I came up with a gimmick. It looks like function overloading.

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.

Simple functions to display a hex dump of a byte array using sequence expressions, with ASCII. Rewrote naive version that used string concat, based on optimizations in http://fssnip.net/ht, and cleaned up ASCII formatting.

Quick function to take a wireshark 'C Structure' and turn it into a F# byte array

Solution to Kata Six: Anagrams from http://codekata.pragprog.com/2007/01/kata_six_anagra.html in F#

This snippet like "dir" function of Python. ( http://docs.python.org/2/library/functions.html#dir ) The "dir" function is useful on fsi. You can take a look at members of the object quickly.

http://codekata.pragprog.com/2007/01/kata_five_bloom.html

A crazy experiment for "Scalable" collections. Inspired by the paper "Fighting Bit Rot with Types"

Making QR-code image having contact information (VCard) with Google Chart API. If you scan this image with mobile phone, you can directly add new person to your contacts.

An implementation of the ? operator that handles null

Basic (but experimental) TCP stream wrappers to help make TCP more abstracted and cleaner. Giving the user just the impression of a 'stream' that one connects to and sends and receives. This helps promote composition. The first abstraction is 'stream', really just wrapping .NET stream functions so that read returns the read n bytes and write returns the stream, all functions take NetworkStream as the first parameters, followed by other parameters. Currently we don't care about timeouts, exceptions, or other nasty's.

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.

Here I give an example of a data structure known as a skew binary list and also an example of how to use the cons pattern, normally reserved for FSharp lists, in your own union cases. It is not possible to do the same with the nil union case, []. Nor is it possible to use any other symbols (as far as I know). This kind of sucks.

This pattern shows that by using a few static member constraints, one can create an assortment of data processing functions that emulate higher level typing than is possible in F#.

A few active pattern combinators useful when pattern matching on lists is necessary.

Project Euler Problem 14

Given an input stream of "int|int" pairs (one such pair per line), output only those lines for which the right integer has at least k distinct integers on the left side, on the entire input stream. The number k is given as a command line argument.

Allows to expose an F# async value in a C#-friendly API with the semantics of Lazy<> (compute on demand and guarantee only one computation)

An abstract class that implements all the boilerplate required for custom comparison semantics.

F# Simulation lab Part III Systems Biology Cambridge University

F# Simulation lab Part III Systems Biology Cambridge University

This is the code I used to generate this pie chart: http://pic.twitter.com/PgPEFByg56 Enough said?

Agent that can upgrade its functionality on the fly. (F# MailboxProcessor containing function in the loop...)

Estimate the value of PI using a Monte Carlo simulation.

Evaluates a useful subset of F# quotations at run-time (without the F# PowerPack API).

F# to CSS compiler (CSS EDSL in F#) <+> inspired by Clay and FAKE - https://github.com/Cynede/Failess

Comparing university enrollment rate in Czech Republic and OECD countries (works in tryfsharp.org!)

Reversi Kata solution from February 2013 London F# Meetup Coding Kata.

The Nancy web framework parses URLs for you, and passes requests under a given URL route and HTTP method to your program. It relies heavily on C# dynamic objects; these don't translate well in F# code, and it's easy to make mistakes that only show up at run time. Here we define one F# record type for each route, with an attribute that defines the URL, with placeholders for each field in the record. These types implement one generic interface for each HTTP method they support: for GET, PUT and POST, these generic interfaces also specify the types of the HTTP request and response bodies.

A proof of concept on how one could build an argument parsing scheme simply by declaring a discriminated union.

Fast and GC friendly fixpoint combinator.

Builds a Visual Studio solution.

Or who needs non-strict semantics when you have references?

Accepts a directory and wildcard pattern to delete files in a folder

Copies a directory of files. Based on code from http://msdn.microsoft.com/en-us/library/bb762914.aspx

Implemetation picked up from http://msdn.microsoft.com/en-us/library/system.runtime.serialization.objectmanager.aspx

Generate password-like string and save it to clipboard. Original idea is here: http://d.hatena.ne.jp/rubyco/20130202/password (Japanese)

This fake module can trace pipeline operators.

hackthissite.org programming level 12, string manipulation.

Defines the operator /% as DivRem for int, int64 and bigint.

Compute the factorial of a given number by building the list of permutations of the list of first n numbers [1..n] and taking its length

If I'd entered the same SuperBowl Pool every year, and received the same numbers every year, how much would I have won?

Easy database access.

An F# implementation of Jessica Kerr's blog post on imperative to functional. http://blog.jessitron.com/2013/01/from-imperative-to-data-flow-to.html

A construct that caches the result of a computation/request up to a given expiration interval. Makes use of the atom implementation found in http://fssnip.net/bw

Minimal code to render some colored triangles.

A compute shader using wang's hash to make a static filled window. Runs at 2000 frames per second on my machine.

This is the minimum F# code required to run and view a compute shader with SlimDX in DirectX 11.

A simple implementation that protects the nested workflow from external cancellation. The external cancellation token is passed as an argument for cooperative cancellation. Kudos to Gian Ntzik for this one.

Type Safe Higher-order abstract syntax via GADT encoding

let erfinv x = let mutable p = 0.0 let mutable w = -log((1.0-x)*(1.0+x)) // corrected sign if w < 5.000000 then w <- w - 2.500000 p <- 2.81022636e-08 p <- 3.43273939e-07 + p*w p <- -3.5233877e-06 + p*w p <- -4.39150654e-06 + p*w p <- 0.00021858087 + p*w p <- -0.00125372503 + p*w p <- -0.00417768164 + p*w p <- 0.246640727 + p*w p <- 1.50140941 + p*w else w <- sqrt w - 3.000000 p <- -0.000200214257 p <- 0.000100950558 + p*w p <- 0.00134934322 + p*w p <- -0.00367342844 + p*w p <- 0.00573950773 + p*w p <- -0.0076224613 + p*w p <- 0.00943887047 + p*w p <- 1.00167406 + p*w p <- 2.83297682 + p*w p*x

Sort a list by a frequency distribution. Frequency is calculated as per a a provided function. In the test case a list of lists is sorted by the frequency of the length of the lists.

The example shows how to extend F# 3.0 'query' builder with a new custom operation that will work with standard lists, but also with queries that are translated using LINQ expressiont trees (such as databases).

Church numerals via rank-2 polymorphism

A staged intepreter that embeds a DSL in F#. Translated from MetaOCaml. Details in this paper http://www.cs.rice.edu/~taha/publications/journal/gttse07.pdf

Writing functions that recursively generate lambdas from a given parameter is a useful practice, but things get trickier when you need the output functions themselves to be mutually recursive. This is my attempt at creating a fix-point combinator that transparently handles this requirement. It also gives memoization for free as a side-effect.

Dynamic programming is equivalent to recursion + some way to remember the results (as far as I undertand) The y combinator allows to "tie" a previously "untied" recursion, which itself allows to compositionally inject additional steps in the recursion. This allows to go from recursion to dynamic programming in a structured way. This exemple is a bit contrived, as there are no overlapping subproblems, which would be the case in more interesting problem (dtw etc..)

A small snippet that groups sequences of arbitrary unions by branch type.

Hex string to byte array via sequences

translation of http://www.cs.cmu.edu/~rwh/introsml/techniques/memoization.htm , no particular reason, just satisfying a tangent, read the cmu site for comments & insights.

test

Generate the powerset of a set using a bit pattern.

The Facet Pattern Used for Principle of Least Authority (POLA) Inspired by: "The Lazy Programmer's Guide to Secure Computing" http://www.youtube.com/watch?v=eL5o4PFuxTY

Example of Lift Curve

Example of Lift Curve

Had a C tool to parse a csv of queries and check registry against query, then spit out the result, was horrible to parse and model the data in C (just too much code) so I have converted it to F#.

This is my first experience to write scripts on F# that's why I'll be pleased if somebody will make this snippet more perfectly. Usage: fsi hasher.fsx foo test.dat test.txt bar

Variations on some of the LINQ extension members which do not require a type annotation on the lambda argument when used from F#

This is an attempt to define a workflow that contains reversible stateful computations. In the event of an exception being raised, all insofar successful operations will fold back to their original state. The implementation uses the notion of reversible computation primitives, which are composed using a free monad that is interpreted with a trampoline.

got distracted and decided I wanted to be able to 'disassemble' a function inside of FSI, much like you can do in many Lisps, this isnt very complete and I think it will only work on the most basic functions, but it was very challenging to get working so I thought I would paste it.

another test

only a test

only a test

A snippet exported from Try F#.

When interfacing .NET libraries that potentially yield null values, a lot of boilerplate code is required to ensure no NullReferenceExceptions are raised. This is an attempt to avoid such repetition with computation expressions.

given an array n generates all lists with k choices from n

A snippet exported from Try F#.

A snippet exported from Try F#.

A snippet exported from Try F#.

A snippet exported from Try F#.

A snippet exported from Try F#.

A snippet exported from Try F#.

F# necessarily forces you to explicitly cast between int and float for operations such as division. This is necessary because implicit conversion would make type inference much harder. However having to cast all the time in your code can be a pain. These operators reduce the overhead to one or at most two characters of code.

Take a sequence and exclude values from it based on another 'suppression list' sequence.

Many datasets, particularly those which span several orders of magnitude, have a special property. About 30% of the initial digits of all the data items will be the digit '1'. This can be used to detect fraud, for instance in expenses claims, as people tend to concoct figures which don't have this property. These functions implement one possible test for matching Benford's law. (Credits in the comments.)

A snippet exported from Try F#.

A snippet exported from Try F#.

A snippet exported from Try F#.

A snippet exported from Try F#.

A snippet exported from Try F#.

A snippet generated by Try F#

It's comparatively hard to enumerate files in a directory and subdirectories without getting exceptions for items you don't have permission to read. Here's a function which just ignores items you can't read and enumerates everything else. Useful for searching big network shares.

A script exported from Try F#

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.

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.

fibonacci by Seq.Unfold

Factorial versus tail recursion

The dominator of array A is the value that occurs in more than half of the elements of A. It is a zero-indexed based array consisting of N integers (A [] with N length). To find the index array of the dominator from a A [], we can use a helpful function from Seq module call 'Seq.groupBy' to mitigate the implementation of a solution.

F# Mocking library with a fluent interface Moq users should find familiar. Generate mocks for interfaces and abstract types. Supports mocking methods, properties and events. Specify arguments as wildcards or values to match. Define results as values, computed values or exceptions.

According to Wikipedia, the maximum sub-array problem is a programming task of finding the contiguous sub-array within a one-dimensional array of numbers (containing at least one positive number) which has the largest sum. The following is an attempt to solve this problem by using F# list rather than array.

Break a sequence into sub-sequences, where the break occurs at points where the specified function returns true when provided with the n'th and the n+1'th elements of the input sequence.

A function that returns a sequence of subsets generated by the power set of a specified set. The function use bit patterns to generate sets. for example the power set generated by a set with 3 elements set [1;2;3;] has 2^3 sets. each set in the power set is represented by the set bits in each of the integer from 0 to (2^3) -1

Generate a Conway "look and say" sequence. Each sequence element is generated by reading the previous element from left to right and saying how many repeats of each item there are. Eg. 1211-> 111221 (ie. "one one, one two, two ones").

Create a list of int in range [init, upper).

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.

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.

Yet another immutable queue implementation

Returns a value indicating whether the specified phrase occurs within the given text.

This Joint Life Annuity calculation relies on the objects and functions defined in Single Life Annuity. A joint life annuity calculates the present value of an annuity from current age to death of a member and another life (spouse). The implementation below uses the AgeVectorBuilder from the Single Life Annuity snippet in two examples: The first defines a simple Joint Life Annuity that assumes no age difference between the two lives. The second assumes an N year age difference. The samples both rely on a male mortality table (PMA92 (C=2003)) and a female mortality table (PFA92 (C=2003)) which are extracts of publicly available mortality tables (http://www.actuaries.org.uk/research-and-resources/documents/pma92-pensioners-males-amounts).

An equilibrium index of this array is any integer P such that 0 ≤ P < N and the sum of elements of lower indices is equal to the sum of elements of higher indices. The following is an implementation of such equilibrium list (given the input is a list).

Generates the Prime Number Sequence.

References and type definition to open StackOverflow API over OData

Playing with Undertone, using operators for terse tune definitions.

The Official Solution.

FsSql is originally here: https://github.com/mausch/FsSql and better sample is there too but I just want to share it.

Quick & dirty solution to Reversi kata: http://codingdojo.org/cgi-bin/wiki.pl?KataReversi

Normally, when we implement Fibonacci sequence, we use recursive function, but it will encounter the overflow exception with the big data. Below is the Fibonacci snippet with continuation, and in this way, it won't encounter the overflow exception.

A quick exploration of the rather useless question "how does the density of the product of 2 sparse matrices look like?"

An Implementation of the Porter Stemming Algorithm in F# for text analysis. Please see: http://tartarus.org/martin/PorterStemmer/

A random pex4fun puzzle to write a snippet to merge two strings.

Simple combinator library to declarative validation.

Formal Concept Analysis (FCA) is a method to determine cohesive groupings of functions and data structures, especially in program comprehension research. For example, consider an object set, O = {1,2,3,4,5,6,7,8,9,10}, and an attribute set, A = {composite,even,odd,prime,square}, we can build a lattice table that holds the relations between O and A.

This function splits a sequence into lists of length n until there is less than n elements then those are returned.

Immutable stack can be implemented via Discriminated Union Type with methods like Push and Pop. The following snippet is a simple version of it.

This snippet defines a computation builder that sums the squares of float values. It includes Combine, Zero, Yield, Delay, and For operations.

Adds "enumerable extraction" support to query expressions

An implementation of the inverse of Expr.Cast<_>, with erasure happening at reflection level.

the function returns entire files sequence for given root directory, including sub-directories.

it's quite easy to define a modifiable static property in C# , but in F#,a defined static filed is required first when the class want to define a static property.

When we defined an F# class in explicit way, it's easy for new F# programmers to make this kind of mistakes when they define mult constructors: people will forget to initliza the class first before use it.

It's not easy for F# programmer to deal with the unsafe code, here I tried to provide a small code snippet to demonstrate the issue.

It's not convenient to get the memory address of object in F#, and the following code will illustrate how to get the memory of given index item of an array:

Score a Bowling game. The game is represented as a list of integers. A game of bowling consists of ten frames. In each frame, the bowler will have two chances to knock down as many pins as possible with his bowling ball. If a bowler is able to knock down all ten pins with the first ball, he is awarded a strike. If the bowler is able to knock down all 10 pins with the two balls of a frame, it is known as a spare. Bonus points are awarded for both of these, depending on what is scored in the next 2 balls (for a strike) or 1 ball (for a spare). If the bowler knocks down all 10 pins in the tenth frame, the bowler is allowed to throw 3 balls for that frame. This allows for a potential of 12 strikes in a single game, and a maximum score of 300 points, a perfect game.

Another version of QuickSort implementation.

Simplification of 'Apply operators to Options' http://fssnip.net/ee using higher order functions. Should also be part of the Option module.

Simple function to apply operators to option types. Applies the operator to each value and returns a new option containing the result. Treats None as the operator's identity element (i.e., ignores it).

A simple example showing how to use Quartz.NET, an open source job scheduling system, with FSharp.

A type which generates a Latin Square - ie. an n x n array where no value is repeated in any one row or column. Useful in experimental design and some forms of testing. The argument is generic so you can generate a Latin Square of ints, floats, strings, dates, classes etc. (Needs some optimisation - this is a first cut!)

Merge Sort falls into 'Divide and Conquer' problem solving technique and it is a stable sorting. The worst case of running time is (nlogn). This implementation below follows the two abstract steps to achieve Merge Sort, i.e., * Recursively divide input list into two sub-lists. * Repeatedly merge the sub-lists.

A continuation function takes the result when it is computed. Here is an implementation of sorting on List via insertion.

This version of FizzBuzz uses forward composition instead of recursive pattern matching (see http://fssnip.net/e7). All the rules, including the default case, are in a list of lambdas that can be easily modified. The function executeRules composes the list into a single rule and executes it.

Inspired by http://dave.fayr.am/posts/2012-10-4-finding-fizzbuzz.html Rules are in a list of lambdas that can be easily modified. A pattern-matching recursive function applies them in the correct order.

Lists are pointers to the head of list. It can be defined by a discriminated union type. Using continuation can do a tail-recursion version of appending two lists.

A Simple Implementation of Lazy Type.

Applying functions on the n first elements

fold by applying a list of function to a list of arg, last one behaving as usual

Want to do a SqlBulkCopy into a table which has an IDENTITY column? If your DataTable has the same columns as the target (but without the ID), you can map the columns numerically, skipping the first target column.

Readonly generic Hashtable class implementation example.

Creates all possible mobile phone letter combinations from a number.

Generates the value string for the "Authorization:" header given Twitter application/user keys and tokens and the parameters for the request being authorized.

Generates the value string for the "Authorization:" header given Twitter application/user keys and tokens and the parameters for the request being authorized.

work with ini file with WritePrivateProfileString, GetPrivateProfileString easy as pie

Sample for Coding Kata

An implementation of a CRC-32 algorithm, as described in RFC-1952 "GZIP file format specification version 4.3"

Square root for integral types

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

Code by me and Nick Palladinos.

This is an implementation of the Async.Choice combinator that composes a sequence of workflows into one whose result is that of the first workflow that returns a *valid* result. You can think of it as a nondeterministic version of (Seq.tryPick id). This implementation draws ideas from Tomas Petricek's choice implementation in http://fssnip.net/6D.

A simple extension method for asynchronous non-deterministic computations.

This sample illustrates how to use an IDisposable inside an object, as well as a simple use of object expression

A simple utility that allows making assertions using potentially complex pattern matches.

A monadic trampoline for stack-overflow free programming.

A batched Deque

A simple domain specific langauge (DSL) that can be used to specify and recognize patterrns in 2D arrays. A pattern is defined by composing primitive checks, rotating and translating patterns. See also: http://t.co/6Poty4FL

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.

A pair of extension methods for SerializationInfo that make custom ISerializable implementations much more straightforward to write.

Here's how to use the [<Theory>] and [<InlineData>] attributes to throw a set of data at a single test.

Naive "school-book" implimentation.

This is a simple script which, recursively walking a folder structure, updates .fsproj files so they may be run in VS2012 or VS2010. This should be run *after* VS2012 has converted a particular solution. Also, I didn't really test it too much, but it worked for me. So there's your disclaimer.

simple affineCipher translated from https://github.com/asweigart/codebreaker/blob/master/affineCipher.py not sure if actually correct

A simple script to list the exceptions that can be thrown during the method invocation (both caught and uncaught).

The snippet implements 'map' and 'init' functions for the 'ObservableCollection' type. These are similar to well-known functions for sequences, but 'map' works in an incremental fashion. When the source collection changes, the resulting collection is updated.

This script generates a file named __project.fsx, for each proejct which can be #load "__project.fsx" in script intending to use the same dependency graph as the code in VS a file named __solmerged.fsx, at the solution root which can be #load "__solmerged.fsx" in script intending to use the same dependency graph as the code in VS In both cases, this enforce that : **a script compiling in VS should run from FSI **

A minimal interpreter for David Madore's crazy-esoteric programming language.

just some snippets ive been using to play around with async + DNS, nothing production, updated: ipsOfDomain and domainOfIp now both return string array

When versioning a solution, I like to just version the packages.config and not the binaries themselves. that means upon checkout, one has to install the referenced Nugets. This is the purpose of this script. [For some reason you have to press 'enter' between commands..]

failwith/failwithf are a useful operators, but they only raise exceptions of type SystemException. Here's a simple way to generalize them.

An implementation of John D. Cook's algorithm for fast-finding perfect squares: http://www.johndcook.com/blog/2008/11/17/fast-way-to-test-whether-a-number-is-a-square/

The following is a simplistic implementation of global events, which is the precise dual of the dependency injection implementation found in http://fssnip.net/dg. This is just a proof of concept, unwise to use in real life.

This is a simple IoC implementation that allows registration with optional parametrization.

Implementation of Project Euler question 28.

Calculating the Earth Similarity Index of a planet. http://phl.upr.edu/projects/earth-similarity-index-esi

Rename JSON property names by reconstructing JSON object.

Conway's Game of Life example at F#unctional Londoners July 2012 meetup.

A bit of syntax eye candy for your string building code.

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.

An experiment on type-level computations.

This simple tool is useful for string based approvals testing. When tests are run in DEBUG mode, the code opens the p4merge diff tool (change it to point to yours) to clearly show the differences between the expected and actual strings. The actual, or received string is copied, in escaped form, to the clipboard so that it can be easily pasted into the associated test to approve the changes if appropriate. When a debugger isn't attached, this tool reverts to using a standard Assert so that it won't attempt to open a diff viewer when executed on a CI server.

Single level retro game playable inside TryFsharp using the cursor keys.

A small DSL for graph building by combining weighted paths. It's just a map of edges to weights under the hood, so no need to worry about duplication causing problems. This is part of a larger project I'm calling edgy.

A small DSL for graph building by combining paths. It's just a set of edges under the hood, so no need to worry about duplication causing problems. This is part of a larger project I'm calling edgy.

Simulation and performance measurement of a single-server queue with various arrival and processing rates configurations. More comments on this can be found at http://www.clear-lines.com/blog/post/Simulating-a-simple-Queue-in-FSharp.aspx

The following is an implementation of a general-purpose pretty printer for tables. Its generality is achieved by passing an upcast rule to an untyped record type as argument.

Simple implementation of Conway's Game of Life for the TryF# web site.

Encoding mutually-recursive functions with a Polyvariadic fixpoint combinator.

seq to IEnumerator and IEnumerable

AI

Tiny robot simulate, it's available to run on tryfs.net (but not on iPad).

Quick benchmark to compare the throughput performance of F# MailboxProcessor using asynchronous workflows and a synchronous agent using a lock and busy loop. The latter is 9x faster on this machine.

When passing objects as arguments to F# functions, it is almost certain that a type annotation will be required. This may generate long and noisy code at times, but thankfully we can use active patterns to mitigate this annoyance.

Function to generate color values to reflect the relative intensity of numeric values in a range. --- Fixed edge case of when max=min

The generic model for stateful computation (S -> S x R) provides a convenient mechanism of threading stateful computation results since the functor λR . S -> S x R is monadic. But what happens if we want to thread state itself? Well, the mapping λS. S -> S x R is not even functorial! But it turns out it can become so with a bit of trickery. This snippet demonstrates a way to lift, project or inject stateful computations into ambient state monads.

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.

This snippet generates a punched card image from a text. It punches holes in the places where a letter would be written and you can use it to generate jokes such as this one: http://bit.ly/M2oqOw

An ASCII Mandelbrot visualisation. (Suggested by a tweet from Jon Harrop, but any bugs are mine.)

A version of Seq.skip which doesn't throw an exception if there are fewer lines in the sequence than you have asked to skip.

have a project to write some basics from gzip, needed crc32, seems fast enough!

This is a small fsx script that views the current 'it' value of Fsi in a PropertyGrid. How to use it: - Copy the source code into a file called FsiProp.fsx and place it next to Fsi.exe - Start Fsi.exe with --load:FsiProp.fsx - Maximize Fsi.exe for full enjoyment. (I placed the PropertyGrid Form on the right screen half.) (Make a .lnk to this if you find it useful, there set Maximize on Fsi.exe) Take FsEye if you want to see what's in 'it' in detail. But you cannot change it there. ;)

Given an ordered set S and an arbitrary set T, any function T -> S induces a natural ordering on T. We use this idea and the infrastructure provided by Tagged.Set to quickly construct sets over arbitrary types with custom comparison rules.

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!

Yet another tutorial based on the DSL for modelling financial contracts. This is a walkthrough with examples and tasks that is loaded by the previous 'Setup' snippet. Designed to run in Try F#.

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

Sample code using a simple library for downloading Yahoo stock prices. The demo shows how to process sequences and so on (to run this, load & run previous snippet).

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