1719 result(s)
Two functions showing how to filter functional lists using the specified predicate. First version uses naive recursion and the second one is tail-recursive using the accumulator parameter.
77 people like thisPosted: 15 years ago by Tomas Petricek
Three functions showing how to implement projection for functional lists. First version uses naive recursion and the second one is tail-recursive using the accumulator parameter. The third version extends this with continuation passing.
75 people like thisPosted: 15 years ago by Tomas Petricek
Create sequence of floating point values generated by random walk process. Functional solution using sequence expressions and yield! construct in a tail-call position.
39 people like thisPosted: 15 years ago by Tomas Petricek
Windows Forms tutorial showing how to create form with button and how to register an event handler. When the button is clicked, the form changes its background color.
49 people like thisPosted: 15 years ago by Tomas Petricek
Classical "Hello world" example that prints a message to the console output. This version uses F# printfn function to do the printing.
186 people like thisPosted: 15 years ago by Tomas Petricek
Classical "Hello world" example that prints a message to the console output. This version uses .NET Console.WriteLine method to do the printing.
31 people like thisPosted: 15 years ago by Tomas Petricek
Generates a friendly string describing a date relatively to the current date and time. The function returns strings like "2 secs ago", "yesterday" or "3 years ago".
42 people like thisPosted: 15 years ago by Tomas Petricek
Show's how to use F# 'use' key word to dispose a resource when it passes out of scope.
34 people like thisPosted: 15 years ago by Robert Pickering
This snippet uses the lazy keyword to create a delayed computation. It then show's using 'force' to evaluate the computation.
27 people like thisPosted: 15 years ago by Robert Pickering
Demonstrates using the 'lazy' keyword. Show's how a lazy value will only ever be evaluated once.
45 people like thisPosted: 15 years ago by Robert Pickering
Show's using the unfold function to create a sequence that terminates once some limit is passed.
39 people like thisPosted: 15 years ago by Robert Pickering
Show's how to define a recursive function that will calculate a fibonacci number.
16 people like thisPosted: 15 years ago by Robert Pickering
Shows how to use an active pattern that will try to determine the format of an input value.
17 people like thisPosted: 15 years ago by Robert Pickering
Show's how to create a parametrized active pattern that will match based on a regular expression.
34 people like thisPosted: 15 years ago by Robert Pickering
Show's how to define units of measure to add stronger typing to your numerical functions.
75 people like thisPosted: 15 years ago by Robert Pickering
Add extension to System.Type that returns the name of type including generic arguments in a nice readable format. It returns only short names of generic type and type arguments.
21 people like thisPosted: 15 years ago by Tomas Petricek
The snippet shows how to support slicing in a type. Slicing allows you to get for example a 2D sub-matrix of a matrix and is implemented by adding GetSlice member.
49 people like thisPosted: 15 years ago by Tomas Petricek
Random walk on integers starting at zero. At each step, we either add or subtract one depending on a random coin flip. The code uses Seq.unfold to generate infinite sequence.
53 people like thisPosted: 15 years ago by James
This example shows how to load a Xaml file allowing to use WPF from F#. It also shows how to access WPF objects and register event handlers.
109 people like thisPosted: 15 years ago by Antonio Cisternino
Currying is about fixing arguments of functions from left to right. It's useful to configurate code and embed parameters that usually serve to define the context of a function execution (i.e. a database connection object). Symbolic functions can be used to reorder arguments if needed.
20 people like thisPosted: 15 years ago by Antonio Cisternino
Handy *printf feature: use kprintf to prepend datetime to formatted message
54 people like thisPosted: 15 years ago by Vladimir Matveev
Disable printf based on some condition
41 people like thisPosted: 15 years ago by Laurent
Some simple functions for writing more idiomatic F# tests with NUnit.
91 people like thisPosted: 15 years ago by Ryan Riley
Bit manipulation methods
53 people like thisPosted: 15 years ago by Andrei Logunov
Calculates the factorial for positive integers
26 people like thisPosted: 15 years ago by Stefan Knoblauch
Composition of functions in F# is easily achieved by using the >> operator. You can also chain an arbitary amount of functions (represented as a list or sequence) together by folding the list/seq with >>. [More formally: the set of endomorphisms 'a -> 'a forms a monoid with the binary, associative operator ">>" (or "<<") and the neutral element "id".]
87 people like thisPosted: 15 years ago by Novox
This snippet provides a very small internal DSL for creating and querying XML using the underlying XLinq classes.
374 people like thisPosted: 15 years ago by Blake Coverett
I use this basic template when writing .fsx files that I might want to compile. It adjusts the difference in command line/entrypoint handling between a script and a compiled assembly. This example shows the details for a WPF script — replace the #r's and/or remove the STAThread for a WinForms or Console script.
127 people like thisPosted: 15 years ago by Blake Coverett
The modified Random type is built on top of System.Random type. It has a member Seed which returns a seed and NextFloat has the same overloads as NextInt (Next in System.Random). The members should further support units of measure.
17 people like thisPosted: 15 years ago by Oldrich Svec
This class is a 3D vector representation. There is a module called Triple with operations on the triple type.
27 people like thisPosted: 15 years ago by Oldrich Svec
Continuations provide a means whereby heap space can be traded for stack depth (heap space being generally more plentiful than stack depth). They are especially useful where tail recursion is not possible. Here are a couple of simple continuation examples that can be extended to cover more complex scenarios.
100 people like thisPosted: 15 years ago by Neil Carrier
Functional style Regex engine
21 people like thisPosted: 15 years ago by Nick Palladinos
Here is an improved version twice shorter, than original
72 people like thisPosted: 15 years ago by Nick Canzoneri
The function segmentSegment takes 2 segments (starting and ending points) and computes the shortest distance between them. The function returns a starting and ending point of the shortest segment between the two segments. The function uses a triple type but can be easily rewritten to work with any other type (vector etc).
30 people like thisPosted: 15 years ago by Oldrich Svec
While prototyping programs I find myself using association lists. This little snippet defines a lookup functions for association lists defined as lists of tuples.
68 people like thisPosted: 15 years ago by Alex Muscar
Analog to the fst and snd functions of the f# lib some functions for tuples with 3 values which i use quite regularly during prototyping phases.
27 people like thisPosted: 15 years ago by daniel szymanski
Implements iterate function from Haskell's Prelude. The function generates an infinite sequence by applying a function to the initial value (first) and then to the result of previous application.
203 people like thisPosted: 15 years ago by Nick Palladinos
The const function is simple, but you can use it to make your code more legible. In this example we convert a unary function to a function of arity 2 (that ignores the second argument). Also by using the flip function from Haskell (which is equally easy to define) you can ignore the first argument.
119 people like thisPosted: 15 years ago by Alex Muscar
A domain specific language for creating layout using Windows Forms. The snippet implements combinators for creating controls and simple automatic arrangement of them.
43 people like thisPosted: 15 years ago by Tomas Petricek
We start with an initial value and then applying f repeatedly, until the value does not change anymore.
303 people like thisPosted: 15 years ago by Nick Palladinos
This snippet shows how to create objects with events in F#. It shows both simple event (to be used from F#) and a .NET compatible event with specific delegate type.
85 people like thisPosted: 15 years ago by Tomas Petricek
Computes the Cartesian product of a list of lists. See also corresponding example for a sequence of sequences.
49 people like thisPosted: 15 years ago by Neil Carrier
Computes the Cartesian product of a sequence of sequences. See corresponding example for a list of lists.
56 people like thisPosted: 15 years ago by Neil Carrier
Concatenating paths shouldn't be done just using string concatenation, because the directory separator may differ on various platforms. This snippet shows a simple custom operator for working with paths.
27 people like thisPosted: 15 years ago by Tomas Petricek
Shows how to use the 'ExprShape' module to recursively traverse an entire quotation and how to write quotation transformations. As an example, the snippet replaces all numeric constants in the quotation and then runs the transformed code.
27 people like thisPosted: 15 years ago by Tomas Petricek
Some Web sites deny requests that aren't sent by recognized browsers and search engine crawlers. Setting the user agent header of the request is usually sufficient for bypassing this restriction.
36 people like thisPosted: 15 years ago by Taha Hachana
An asynchronous sequence is similar to the seq
Posted: 15 years ago by Tomas Petricek
F# code to fetch a registry key
42 people like thisPosted: 15 years ago by Tuomas Hietanen
I'm working on parallel computations and I thought it would be useful to break work into chunks, especially when processing each element asynchronously is too expensive. The neat thing is that this function is general even though motivation for it is specific. Another neat thing is that this is true lazy sequence unlike what you'd get if you used Seq.groupBy. There are three versions for your enjoyment.
73 people like thisPosted: 15 years ago by Dmitri Pavlenkov
Solution to Project Euler problem 2: Find sum of even terms in fibonacci sequence which do not exceed four million. Comments about the first version: 1. It does't use memoize becouse of recursive call to unmemoized function "fibs". So it take over 20 sec to get answer. A minor change ("fibs" to "fibs' ") reduces this time to 140ms.
35 people like thisPosted: 15 years ago by D
Hi, I expressed Memoization and Memoization Tail Recursive on the functions. I hope something useful.
22 people like thisPosted: 15 years ago by zecl
A lazy enumerable/stream of bytes.
9 people like thisPosted: 15 years ago by Ryan Riley
Extensions to dictionaries.
36 people like thisPosted: 15 years ago by Ryan Riley
Cached fib sequence
16 people like thisPosted: 15 years ago by Dmitri Pavlenkov
LanguagePrimitives help create inline functions
42 people like thisPosted: 15 years ago by Dmitri Pavlenkov
A function for interpreting the zero-based index property of a successful regular expression match in terms of line and column numbers.
22 people like thisPosted: 15 years ago by Taha Hachana
Clojure's Atoms are ref like structures, with the addition of (Compare And Swap) update semantics
30 people like thisPosted: 15 years ago by Nick Palladinos
Closest Pair of points problem in the planar case.
28 people like thisPosted: 15 years ago by Martin Szarski
F# implementation of SelectMany and TakeUntil (from Rx) on F# events
19 people like thisPosted: 15 years ago by Ankur Dhama
Various functions around nullable types
28 people like thisPosted: 15 years ago by Mauricio Scheffer
Async memory or file hashing
11 people like thisPosted: 15 years ago by Mauricio Scheffer
Async wrapper for SmtpClient (which is event-based)
16 people like thisPosted: 15 years ago by Mauricio Scheffer
Sometimes you'd be surprised at what functionality you can find inside the .Net framework. Apparently the DataTable object can compute string expressions. Nice for testing your own parser implementation, and/or for lazy coders like me. Note that the DataTable is created only once and reused with each function call.
35 people like thisPosted: 15 years ago by Arjen Kopinga
A basic, asynchronous TCP server
41 people like thisPosted: 15 years ago by Ryan Riley
Sample code which demonstrate tree searching using : Tail recursion with continuation
16 people like thisPosted: 15 years ago by Ankur Dhama
This function interprets a time span in terms of years, months and days.
27 people like thisPosted: 15 years ago by Taha Hachana
Wraps an Async as an IObservable to allow easier consumption by other .NET languages. Many thanks to desco for his help: http://cs.hubfs.net/forums/thread/16545.aspx
5 people like thisPosted: 15 years ago by Ryan Riley
This function is given a partition predicate and a sequence. Until the predicate returns false, a list will be filled with elements. When it is, both the list and the remainder of the sequence will be returned. Note that this example preserves the laziness of the unchecked sequence elements.
74 people like thisPosted: 15 years ago by Rick Minerich
Depends on Castle Dynamic Proxy 2. Returns an IEnumerable
Posted: 15 years ago by Dan Finch
A more tolerant and open-minded take.
19 people like thisPosted: 15 years ago by Dan Finch
This is used for building things with reflection at runtime. As ConstructorInfo arguments require typed collections, it is necessary when parsing to reflected records to first build up contents and then afterward convert the collected obj[] to a 'a[]. This is finally cast back to obj so it can be used as a ConstructorInfo argument.
29 people like thisPosted: 15 years ago by Rick Minerich
Get Stock Quote Data and Historical Stock Prices from Yahoo Finance.
237 people like thisPosted: 15 years ago by Tuomas Hietanen
Function to generate circular infinite sequence from a list
21 people like thisPosted: 15 years ago by Ankur Dhama
A LazyList implementation with tail recursive enumeration.
39 people like thisPosted: 15 years ago by Nick Palladinos
An easy wrapper for the TPL that works nicely with (|>)
11 people like thisPosted: 15 years ago by Paul Greene
A function that takes every Nth element of a sequence where N is passed as an argument. The snippet shows a naive function and a function using IEnumerator directly to provide an efficient implementation.
36 people like thisPosted: 15 years ago by Tomas Petricek
Function to generate all possible combinations where combination "ab" is different then "ba"
6 people like thisPosted: 15 years ago by Ankur Dhama
Removes from list the first ocurrence only of an element that satisfies the predicate. Additional elements that also satisfy the predicate remain in the list.
54 people like thisPosted: 15 years ago by Alexander Rautenberg
While reading Tomas Petricek's master thesis, came across FIX operator implementation. Decided to experiment with various implementations of factorial.
16 people like thisPosted: 15 years ago by Dmitri Pavlenkov
Clojure's Atoms are ref like structures, with the addition of (Compare And Swap) update semantics
28 people like thisPosted: 15 years ago by Nick Palladinos
This code sample shows how to create a function that raises number to a given power using supercompilation with quotations. For any given power, the function returns quoted expression for calculating the power using explicit multiplications, which is then evaluated.
21 people like thisPosted: 15 years ago by Dmitry Soshnikov
Simple HTTP server with Async workflow and Http Listener
12 people like thisPosted: 15 years ago by Ankur Dhama
Attempt to reimplement functions AsyncRead/AsyncReadLines from 'Rx on the server ' articles (by Jeffrey van Gogh) using idea of AsyncSequence (by Tomas Petricek)
26 people like thisPosted: 15 years ago by Vladimir Matveev
The RSA encryption is based on the following procedure:
Generate two distinct primes p and q. Compute n=pq and phi=(p-1)(q-1).
Find an integer e, 1 Posted: 15 years ago by
Natallie Baikevich
Like the snippet!
The Let active pattern demonstrated by this snippet can be used to assign values to symbols in pattern matching. This is useful for writing complex pattern matching using match as we can handle multiple cases using a single clause.
64 people like thisPosted: 15 years ago by Tomas Petricek
This function produces safe URLs for Web requests or URI construction. It forces the pattern: http:// + www. OR subdomain. + domain + absolute path. When used in an application that takes URLs as input, the user would be able to type "example.com" instead of "http://example.com" or "http://www.example.com". It also supports domains like google.co.uk or google.com.au.
8 people like thisPosted: 15 years ago by Taha Hachana
This code sample generates Pascal's triangle as jagged 2D list (list of lists).
19 people like thisPosted: 15 years ago by Dmitry Soshnikov
Let's use the fundamental theorem of arithmetic to determine if two words are anagrams of each other. How? The theorem states (roughly) that each number can be written as a product of prime numbers in only one unique way. For instance 42 = 7 * 2 * 3 = 3 * 7 * 2. Now what will happen if you associate a letter with a unique prime number? You can see that "team" [71*11*2*41] = "meat" [41*11*2*71]. Oh, the possibilities. Note that in the code below big integers are used since the product of many primes will overflow a 32- or even a 64-bit integer.
25 people like thisPosted: 15 years ago by Arjen Kopinga
Performs conversions to and from hexadecimal values.
28 people like thisPosted: 15 years ago by Daniel Robinson
Quotes SQL Server identifiers. Handles embedded quotes.
2 people like thisPosted: 15 years ago by Daniel Robinson
Splits strings lazily, instead of splitting entire string into an array like System.String.Split. Especially useful for very large strings.
7 people like thisPosted: 15 years ago by Daniel Robinson
Converts string to Pascal or camel case. Useful mostly for identifiers. Uses case changes to determine word boundaries.
4 people like thisPosted: 15 years ago by Daniel Robinson
Active pattern returning list of captured groups.
11 people like thisPosted: 15 years ago by Daniel Robinson
The window is useful when you want to print out data to the screen.
14 people like thisPosted: 15 years ago by Stefan Knoblauch
This code sample generates Pascal's triangle as jagged 2D list (list of lists). It takes 0.5 sec to generate 3000 rows (vs 16 sec for http://fssnip.net/23). Tip: try to avoid of using "list1 @ list2" construction.
14 people like thisPosted: 15 years ago by Shamil Sayfutdinov
Haskell-inspired infinite sequences
48 people like thisPosted: 15 years ago by Nick Palladinos
Merge two events in one event to move over a list. Can be used to implement a wizard / slider mechanism
18 people like thisPosted: 15 years ago by Ankur Dhama
A Uri parser using the Cashel library [1]. This implementation is using ArraySegment
Posted: 15 years ago by Ryan Riley
A functional wrapper around the new WCF Web APIs (http://wcf.codeplex.com/). Composition is achieved through the use of the HttpRequestMessage -> Async
Posted: 15 years ago by Ryan Riley
LinkedList functional extension providing find and findi higher order functions that take a predicate function.
41 people like thisPosted: 15 years ago by Phillip Trelford
A simple Quine in F#
24 people like thisPosted: 15 years ago by Nick Palladinos
Sorted Map
18 people like thisPosted: 15 years ago by fholm
Petrovich is more than just a programming language, it is a complete computer operating system and program development environment named after Ivan Petrovich Pavlov. Design Principles: * Provide an operating system and computer language that can learn and improve its performance in a natural manner. * Adapt to user feedback in an intelligent manner.
12 people like thisPosted: 15 years ago by Natallie Baikevich
Demonstrates how to run a function when the user presses Ctrl+C, closes the console window, or logs off.
31 people like thisPosted: 15 years ago by Tim Robinson
This snippet shows how to plot data on a form using .NET 4.0 Chart control.
37 people like thisPosted: 15 years ago by Dmitry Soshnikov
Example of annoying enumeration syntax
13 people like thisPosted: 15 years ago by fholm
Randomizes order of specified sequence
24 people like thisPosted: 15 years ago by Phillip Trelford
Searches all (currently loaded) types using Reflection to find the types with longest and shortest names of members. Uses average length of all type member names as a metric.
13 people like thisPosted: 15 years ago by Tomas Petricek
A Clojure inspired (race free) memoize function, that uses a mutable atom cell.
21 people like thisPosted: 15 years ago by Nick Palladinos
Computation builder that provides easy way of constructing IDisposable objects. It supports elegant composition of disposable objects using 'do!' which can be used for example when working with 'IObservable' type.
42 people like thisPosted: 15 years ago by Tomas Petricek
Code to parse HTTP chunked response, to use as a client to a Comet server who uses chunked encoding to transfer real time notification data
3 people like thisPosted: 15 years ago by Ankur Dhama
Miller–Rabin primality test is an algorithm which determines whether a given number is probable prime. For more information go to http://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
34 people like thisPosted: 15 years ago by Cesar Mendoza
The ObservableObject type implements the INotifyPropertyChanged interface used in WPF and Silverlight to notify on changes to properties that are bound to a control. Specify property names type safely using F# Quotations, i.e. <@ this.PropertyName @> when invoking the NotifyPropertyChanged method. If you are following the MVVM pattern then your View Model class can inherit from the ObservableObject type.
69 people like thisPosted: 15 years ago by Phillip Trelford
For a given list, find all possible combinations of elements of the list (not just k-combinations). The result is a list of lists with each element representing one combination. Order of elements is not taken into account.
30 people like thisPosted: 15 years ago by Alexander Rautenberg
Cartesian product of a variable number of lists. Input is a list of lists of which the cartesian product is to be constructed; output is a list that contains the elements of the product set, as lists.
16 people like thisPosted: 15 years ago by Alexander Rautenberg
Put the code at some place and enable "Step Into Properties and Operators in Managed Code": http://msdn.microsoft.com/en-us/library/cc667388.aspx Now you should be able to step into the pipeline operator.
35 people like thisPosted: 15 years ago by Oldrich Svec
get the list of ethernet sql servers
90 people like thisPosted: 15 years ago by nCdy
Today, 11. february 2011, is a palindromic day according to the European date format (day/month/year). This snippet collects all the palindromic dates until 31 dec. 9999. They are 366, a surprisingly low number.
13 people like thisPosted: 15 years ago by Francesco De Vittori
The Subject
Posted: 15 years ago by Phillip Trelford
Ugly hack to call F# functions as static methods
5 people like thisPosted: 15 years ago by fholm
Nice thing you can do in F# that you can't do in C#, pulling a reference to an array element as a local var.
26 people like thisPosted: 15 years ago by fholm
F# implementation of RO_ref from the "Effective ML" talk.
93 people like thisPosted: 15 years ago by fholm
Abstracts console input as an infinite sequence of lines of text
7 people like thisPosted: 15 years ago by fholm
You never know when you might need this.
7 people like thisPosted: 15 years ago by Dmitri Pavlenkov
Simple Object orientation using Record types. No complex - private public internal virtual abstract object oriented programming :)
7 people like thisPosted: 15 years ago by Ankur Dhama
Return a sequence that contains the numerators and denominators as tuples for Farey Sequence n.
2 people like thisPosted: 15 years ago by Graham Spiers
Jaro-Winkler is a fast and effective name matching algorithm. For more info see "A Comparison of String Distance Metrics for Name-Matching Tasks" http://www.isi.edu/info-agents/workshops/ijcai03/papers/Cohen-p.pdf or the Wikipedia article http://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance
29 people like thisPosted: 15 years ago by Rick Minerich
This is the struct IronJS uses internally to do NaN-tagging of boxed values, using the technique described here http://blog.mozilla.com/rob-sayre/2010/08/02/mozillas-new-javascript-value-representation/ and here http://article.gmane.org/gmane.comp.lang.lua.general/58908
10 people like thisPosted: 15 years ago by fholm
Caching the function object created
21 people like thisPosted: 15 years ago by fholm
Two/Three/Four-element generic tuples implemented as a value types for writing more efficient F# code.
77 people like thisPosted: 15 years ago by fholm
A higher kind of request to Don Syme... please please please,,,, we desperately need higher kinds!
15 people like thisPosted: 15 years ago by Nick Palladinos
Serialization and deserialization of a function value with Soap formatting. (With serious limitations; not sure how useful this is.)
6 people like thisPosted: 15 years ago by wmeyer
Naive implementation of HuffmanCoding
0 people like thisPosted: 15 years ago by lamer
A small Scheme interpreter using Higher Order Abstract Syntax (HOAS) encoding for terms. The essence of the technique is to use F# (meta-level) functions to encode Scheme (object-level) functions and other binding constructs, thus avoiding the need for representing variables, bindings, explicit substitution and dealing with shadowing.
37 people like thisPosted: 15 years ago by Anton Tayanovskyy
The snippet shows a simple implementation of the dynamic operator (?) that uses Dynamic Language Runtime and the C# implementation of dynamic operations. The snippet shows how to invoke instance methods with single argument.
35 people like thisPosted: 15 years ago by Tomas Petricek
Demonstrates how to implement the dynamic operator (?) using .NET Reflection. The implementation supports calling constructors, propreties and methods using simple overload resolution (based on parameter count). It handles instance as well as static members.
74 people like thisPosted: 15 years ago by Tomas Petricek
F# implementation of a generic Top-Down-Operator-Precedence Parser as described in this paper http://portal.acm.org/citation.cfm?id=512931 Example starts at line ~300
90 people like thisPosted: 15 years ago by fholm
Returns the pascal triangle in a 2D list . This snippet computes rows translating the 'visual' method taught at school into Lists and the usage of map2 function. It takes almost 5 seconds to compute 5000 rows.
21 people like thisPosted: 15 years ago by Horacio Nuñez
This snippet is helpfull in the following cases: 1) After a consolidation operation using the fold function we need to know how many elements have been processed. 2) A consolidation operation needs to use the index of each of the elements processed and we don't want to use the mapi function first. 3) A combination of the above. Since the following snippet just adds a wrapper to the existing Fold function we can repeat the approach for arrays and sequences (including the plinq ones)
31 people like thisPosted: 15 years ago by Horacio Nuñez
A function that efficiently creates a new string containing a given string multiple times. The function is implemented using .NET StringBuilder class.
8 people like thisPosted: 15 years ago by fholm
Union constructors can be used as functions
17 people like thisPosted: 15 years ago by fholm
Perl Style "Regex Matches?" operator
49 people like thisPosted: 15 years ago by fholm
This snippet how we can use F# constructs like discrimated unions, functions and symbolic identifiers to represent proper language statements (albeit limited) using valid F# code.
24 people like thisPosted: 15 years ago by Horacio Nuñez
This pattern is helpful when you want to do something temporarily and then restore some state. This was inspired by the System.Disposable.Disposable() class defined in System.Core.dll distributed by the Reactive Extensions for .NET (Rx) library.
36 people like thisPosted: 15 years ago by Cesar Mendoza
A google search automation.
26 people like thisPosted: 15 years ago by Chief Inspector Clouseau
x = f(x) encoded in F#
22 people like thisPosted: 15 years ago by Nick Palladinos
The snippet defines computation builder for working with IEnumerator. The bind operation (let!) reads next element from the enumerator, so the computation can be used for expressing things that cannot be written just using seq.
29 people like thisPosted: 15 years ago by Tomas Petricek
This is to demonstrate that: (1) there are many ways to solve the same problems; (2) operators can be grouped together into data structures and act as data; (3) you can have fun in F# in many ways.
57 people like thisPosted: 15 years ago by Dmitry Soshnikov
Primitive Pythagorean triples generator. It uses an Algorithm found on Wolfram MathWorld and the F# PowerPack matrix library.
46 people like thisPosted: 15 years ago by Cesar Mendoza
The snippet shows implementing object orientation using mail box processor. In this context object orientation have this simple definition: "Objects acts on message passing". The objects created this way are thread safe too :). Not sure how much practical this would be in todays context where object oriented has gone the wrong way.
28 people like thisPosted: 15 years ago by Ankur Dhama
The snippet shows how to use Microsoft Chart Controls (available in .NET 4.0 and for .NET 3.5) to draw a Bar chart. The sample shows population sizes in different continents.
23 people like thisPosted: 15 years ago by Tomas Petricek
The snippet shows how to use Microsoft Chart Controls (available in .NET 4.0 and for .NET 3.5) to draw a Line chart. The sample generates a 2D spline calculated using sin and cos functions.
11 people like thisPosted: 15 years ago by Tomas Petricek
The snippet shows how to use Microsoft Chart Controls (available in .NET 4.0 and for .NET 3.5) to draw a Candlestick chart visualizing stock prices. The sample uses price of MSFT stocks over 20 days.
17 people like thisPosted: 15 years ago by Tomas Petricek
The snippet shows how to use Microsoft Chart Controls (available in .NET 4.0 and for .NET 3.5) to draw a BoxPlot diagram. In this sample, we provide six statistics (Maxmimum, Minimum, Upper quartile, Lower quartile, Average and Median) about observations explicitly.
23 people like thisPosted: 15 years ago by Tomas Petricek
Normalized Random sequence generator conforming to the user supplied mean and sigma utilizing a "seed factory" instead of the default time of day. The Gaussian sequence is based on the central limit theory, averages together the flat distribution from the random generator built into .NET. Two examples of using normalRand are given to create infinite sequences of white and brown(ian) noise.
45 people like thisPosted: 15 years ago by Tony Lee
Three ways to split a list in half (but not necessarily in the middle). A forth version added that's very short and should be fast, as we only use List.fold. New champ found.
84 people like thisPosted: 15 years ago by Dmitri Pavlenkov
finds the points lying on the convex hull of the given set of points and returns those points in clockwise direction, starting at the point with minimum y-value Remarks: it's a more or less direct implementation of the algorithm named after Ronald Graham that is explained on http://en.wikipedia.org/wiki/Graham_scan you can switch the definition Point for a proper type of your liking - e.g. System.Drawing.Point
39 people like thisPosted: 15 years ago by Carsten König
Declaring WPF DependencyProperty in F#
21 people like thisPosted: 15 years ago by Fahad
Mailbox processors can easily be used to implement active objects. This example shows how to do that with a reusable wrapper type and minimal boilerplate code in the actual class definitions. Supports both asynchronous calls and synchronous calls. For the latter case, exceptions are automatically propagated back to the caller.
92 people like thisPosted: 15 years ago by Wolfgang Meyer
Demonstrates an array initialized from byte literals, which use the 'uy' suffix, and an array initialized from a string byte array literal
48 people like thisPosted: 15 years ago by Tim Robinson
Helpers to convert functions that take a 2-tuple to curried functions and vice versa. Very helpfull for the "Zip"-functor together with operators - see example
45 people like thisPosted: 15 years ago by Carsten König
Helper function to fold an operator over two sequences so {x1; x2; x3; x4; ...} and {y1; y2; y3; y4; ..} is mapped with an operator f to {f x1 y1; f x2 y2; ...} See example
20 people like thisPosted: 15 years ago by Carsten König
shows a simple implementation of a vector and matrix type together with a QR-decomposition using the Gram-Schmidt method. The algorithms themselfes are rather easy but I think the implementation of the types and the computations using recursive techniques might be interessting
3 people like thisPosted: 15 years ago by Carsten König
The snippet demonstrates how to compose simple asynchronous functions and how to use try .. with to handle exceptions in asynchronous workflows.
35 people like thisPosted: 15 years ago by Tomas Petricek
This snippet shows how to construct and query XML using XLinq without too many helper functions.
26 people like thisPosted: 15 years ago by Taha Hachana
F# module to return historical EOD: open | high |low | close | volume quotes from Yahoo. Single day requests only. DataContract provided on the result record for easy serialization.
16 people like thisPosted: 15 years ago by akaPhenom
A minimal TCP/IP proxy implementation with F# asynchronous workflows
24 people like thisPosted: 15 years ago by Ademar Gonzalez
An abstraction of the following use case: Given a sequence of dates and max temperatures for each date, extract out the initial dates on which the temp is greater than a given threshold for n consecutive days. (Originally posted as an answer to this StackOverflow question: http://stackoverflow.com/questions/5267055 )
13 people like thisPosted: 15 years ago by ildjarn
Modular memoization within a pure functional setting that is implemented as a convenient computation builder.
92 people like thisPosted: 15 years ago by Nick Palladinos
Hand-written efficient JavaScript lexer from the IronJS project https://github.com/fholm/IronJS
29 people like thisPosted: 15 years ago by fholm
Asserting a series convergence using high order functions taking for example the 1/pi formula by Ramanujan. Play with the parameters to see where the numeric data types limits makes the function to return false.
24 people like thisPosted: 15 years ago by Horacio Nuñez
Easy dump of record type sequence to file
31 people like thisPosted: 15 years ago by Chief Inspector Clouseau
Demonstrates explicit member syntax as applied to record fields
32 people like thisPosted: 15 years ago by Tim Robinson
Compiler regression in VS2010-SP1 ?
30 people like thisPosted: 15 years ago by fholm
.Net 4.0 added File.ReadLines to view a file as a sequence, but the sequence can only be read once. A simple wrapper with seq{yield!} fixes that.
44 people like thisPosted: 15 years ago by Tony Lee
A function that computes an MD5 hash from a block of bytes. MD5 isn't cryptographically secure, but it's a handy way of condensing a block of data into a short string.
20 people like thisPosted: 15 years ago by Tim Robinson
A snippet that allows you to pretty print source code errors
20 people like thisPosted: 15 years ago by fholm
you can easily find how to use continuations to iterate over a binary tree but what if the count of children for each node is not known at design time? It's not so obvious how to do this in order to get a tail-recursive method. This short snippet shows how to do this to sum the values of every leaf. The second part demonstrates a general approach for other operations than addition.
26 people like thisPosted: 15 years ago by Carsten König
Is it a bug or a feature? :)
1 people like thisPosted: 15 years ago by Oldrich Svec
The code shows simple implementation of blackscholes algorithm.
4 people like thisPosted: 15 years ago by Kishor Aher
The code snippet is capable of calculating historical volatility using Close Price, High Low Price and Close High Low Price methods. Simply provide symbol, start date and end date of the specific volatility method and it extracts the market data from the yahoo service and calculated the volatility.
6 people like thisPosted: 15 years ago by Kishor Aher
This is a search tree for strings I've built for work to back fast type-a-head for AJAX forms, it could be made million times more space efficient but there was no real need for it so.
4 people like thisPosted: 15 years ago by fholm
Definition of the dynamic resolution operators for hosting the DLR. You can either use Ruby or Python, as the module isn't language specific.
4 people like thisPosted: 15 years ago by Rainer Schuster
Populate and displaythe contents of a dictionary with a variable number of nested records - useful if you want to store and retrieve an arbitrary set of data from a database or other data source
3 people like thisPosted: 15 years ago by Brendan Campbell
Yet another attempt of mine to "haskellify" my F# coding.
11 people like thisPosted: 15 years ago by Nick Palladinos
I've modified the CSV sample from Expert F# to my needs. I don't wann be forced to use the csv schema as defined by column rows. Therefore I've done two major modifications. 1. remove the permutation 2. added a new column name option to the ColumnAttribute 3. added a name to csv index mapping So basically you now have 3 options. 1. Don't annotate your record at all and use it as POCO. The order of the record fields is mapped directly to the order in the csv. UPDATE: I don't recommend this any more. As of the writing of this snippet I wasn't aware of the fact, that field order isn't guaranted by the reflection mechanism. 2. Use the index option of the ColumnAttribute. Same as before. 3. Use the name option. This is what I've looked for. I've to deal with tons of csv that has more columns I'm interested in. Have a look at the sample usage below. I've moved the type conversion out of the CsvReader class in order to be easyly expandable with custom type conversation (i.e. for combined column values - denormalized data)
5 people like thisPosted: 15 years ago by Rainer Schuster
Simple snippet that demonstrates recursively defined discriminated unions, the Y combinator (for encoding recursive functions) and recursive processing of tree-like structures
7 people like thisPosted: 15 years ago by Daniel Jackson
Nullable Refs without using AllowNullLiteral
3 people like thisPosted: 14 years ago by fholm
Implements the theory from 'How to write a financial contract' by S.L Peyton Jones and J-M Eber
11 people like thisPosted: 14 years ago by Ademar Gonzalez
Defines an F# computation builder for encoding imperative computations. The 'return' construct returns immediately and terminates the rest of the computation. It is also possible to return value from a 'for' or 'while' loop.
11 people like thisPosted: 14 years ago by Tomas Petricek
Declares an event combinator 'Event.using' that automatically releases resources allocated by a previous event occurence. Each event occurence creates a value using a function specified by the user and automatically calls 'Dispose' when generating a new value.
2 people like thisPosted: 14 years ago by Tomas Petricek
it's allways a pain to work with F#'s Option values outside of F# - there you've got the Nullable-class this is a short snippet to convert Nullable<'a> to 'a option
2 people like thisPosted: 14 years ago by Carsten König
Depicts use of one kind of active pattern matching; partial-case with parameters.
5 people like thisPosted: 14 years ago by Joel Huang
Here is my F# take on some combinatorial functions from the book "Introduction to Functional Programming" by Richard Bird and Philip Wadler.
5 people like thisPosted: 14 years ago by Cesar Mendoza
Solution to the problem mentioned at : http://professor-fish.blogspot.com/2011/01/tiny-bit-of-denotational-semantics.html
1 people like thisPosted: 14 years ago by Ankur Dhama
calculating the distance between two locations on earth using haversine formula see http://en.wikipedia.org/wiki/Haversine_formula and implementing it using the posibilities of F#'s unit of measure system to avoid unit-conversion-errors concerning radians convertet the code found here: http://www.movable-type.co.uk/scripts/latlong.html for an concrete implementation
4 people like thisPosted: 14 years ago by Carsten König
Powerset of set represented as a list. Does not check for repeated elements
2 people like thisPosted: 14 years ago by Andrew Le Couteur Bisson
ML style module example
1 people like thisPosted: 14 years ago by fholm
Wrapped Class/Interface Remark: better this way - see example
1 people like thisPosted: 14 years ago by fholm
Simple implementation of the rope data structure, http://en.wikipedia.org/wiki/Rope_(computer_science)
3 people like thisPosted: 14 years ago by fholm
This snippet provides a way to gain typed access to System.Collection.IEnumerable values (such as instances of System.Text.RegularExpression.MatchCollection), as long as they support a Count property and an Item accessor.
12 people like thisPosted: 14 years ago by kvb
Fast Concatenated String
2 people like thisPosted: 14 years ago by fholm
Efficient Immutable String Concat
4 people like thisPosted: 14 years ago by fholm
Lazy string based on seq
Posted: 14 years ago by Ankur Dhama
This snippet will download the constituents from ftse, stoxx50e,dji,hsi,gspc and store quotes beginning from 1981 into kdb. To get this to work you need to download kpnet from http://kpnet.codeplex.com/ and kdb.
1 people like thisPosted: 14 years ago by Kim Tang
The Untyped Lambda Calculus encoded as actors (F#'s MailboxProcessors)
2 people like thisPosted: 14 years ago by Nick Palladinos
High precedence, right associative backward pipe
7 people like thisPosted: 14 years ago by Stephen Swensen
A broken code example demonstrating how it's you can't catch a single throwing enumeration and continue with F#'s IEnumerable.
2 people like thisPosted: 14 years ago by Rick Minerich
Partitions a sequence into groups linearly by predicate. I use this for breaking up my lazy record parsing with sequences into entity-sized chunks which are then easily digestible. Note: Edited back from the previous edit as these were heavily profiled and yield! tends to be slow. Edit #2: Now correctly using "use" instead of "let" for sequence.GetEnumerator () (Thanks Vladimir Matveev)
1 people like thisPosted: 14 years ago by Rick Minerich
for all those wanting to see the (rather unknown) statical interference of type-parameters (in contrast to generic type parameters) in action. I demonstrated this by having som e fun with basic algebra and polynoms
0 people like thisPosted: 14 years ago by Carsten König
Find every substring that is a palindrome. A bit lazier than the original.
1 people like thisPosted: 14 years ago by Kevin Cantu
computes the list of all permutations of a list for example the permutations of [1;2;3] will be [1;2;3]; [1;3;2]; [2;1;3]; [2;3;1]; [3;1;2]; [3;2;1]
2 people like thisPosted: 14 years ago by Carsten König
Spreadsheet script runnable inside http://tryfsharp.org includes a custom DataGrid and a parser for simple formulas e.g.: =1+1 =SUM(A1,A2) Add your own functions to the evaluate function. For a more comprehensive implementation check out http://cellz.codeplex.com
6 people like thisPosted: 14 years ago by Phillip Trelford
A simple implementation of an Undoable Command, with a Document to hold a stack of actions. 2 examples of UndoableCommand are given - 1 allows property changes to be remembered, and another which allows the user to execute an action with a corresponding undo. Further examples could include CompositeUndoableCommands where the command is itself a list of commands.
0 people like thisPosted: 14 years ago by Neil Danson
Tree implementation using sequences.
3 people like thisPosted: 14 years ago by Ankur Dhama
Seq.filter with accumulator, without using mutable or ref.
2 people like thisPosted: 14 years ago by Ankur Dhama
The snippet declares a helper for creating asynchronous controllers for ASP.NET MVC 3. It declares a new base class for asynchronous actions that exposes a computation builder for writing actions using F# asynchronous workflows.
8 people like thisPosted: 14 years ago by Tomas Petricek
Since F# is my new scripting language, I needed something like Perl's exec but with sequences for Std In and Out.
7 people like thisPosted: 14 years ago by Tony Lee
An asynchronous SNTP client that can retrieve the current time from an internet time server (such as time-a.nist.gov) and optionally update the local system clock to match. Demonstrates async UDP communication, bit-shifting, and native interop/PInvoke.
13 people like thisPosted: 14 years ago by Joel Mueller
This is an attempt to produce similar behavior as seen in the sorted( ) function in Python. Supporting only one of the three optional arguments. The key - Specifies a function of one argument that is used to extract a comparison key from each list element
2 people like thisPosted: 14 years ago by Cameron Frederick
The repmin problem is to replace all elements of a tree of numbers by the minimum element, making only a single pass over the original tree. Repmin is a very ingenious example of Circular Programming.
3 people like thisPosted: 14 years ago by Nick Palladinos
Found an very good article on RS-Trees in Haskell (see: http://www.eecs.usma.edu/webs/people/okasaki/jfp99.ps) It heavyly uses pattern recognition to translate those pesky balance-rules into short code. Bellowe is the simple rewrite of the haskell-implementation in F# - enjoy
6 people like thisPosted: 14 years ago by Carsten König
Facilities for interop with languages supporting null.
4 people like thisPosted: 14 years ago by Daniel Robinson
The snippet demonstrates how to write a general power function that has correct type involving units-of-measure. The function uses numbers represented using types. The snippet is mainly an example of what can be done (not recommended for the real world).
5 people like thisPosted: 14 years ago by Tomas Petricek
A more complete version of sscanf, as proposed on stackoverflow by kvb: http://stackoverflow.com/questions/2415705/read-from-console-in-f Fixed bug in previous version to work with visual studio '13
22 people like thisPosted: 14 years ago by Wolfgang Meyer
Regex match via Active Patterns with Type based value extraction.
5 people like thisPosted: 14 years ago by Nick Palladinos
A partition function on sequences, like List.partition and Array.partition, but yields elements in either partition on demand. Suitable as an extension to Seq.
7 people like thisPosted: 14 years ago by Stephen Swensen
Sample framework for computing Cartesian products using a computation builder.
12 people like thisPosted: 14 years ago by TechNeilogy
A novel, due to performance inadequacy, abstraction of the "tail-recursive loop" pattern. Approaching what a built-in language feature might look like.
3 people like thisPosted: 14 years ago by Stephen Swensen
A simple shortcut for creating temporary files for unit tests.
2 people like thisPosted: 14 years ago by Benjol
Generates SHA512 hash code from a string. Usually used in some kind of validity checks, e.g. check first timestamp and then check SHA-hash over id and timestamp to ensure a valid session.
4 people like thisPosted: 14 years ago by Tuomas Hietanen
ViewModelBase for F# users who want to use it in WPF / Silverlight
16 people like thisPosted: 14 years ago by Fahad
This sample implements "Hello, world!" as a WebSharper application. It demonstrates how to compose HTML/XML using combinators, how to dynamically create a button with a handler and how to update an existing DOM element.
4 people like thisPosted: 14 years ago by Tomas Petricek
Given a period and a sequence of values, calculates the moving average of the input. E.g., given a period of 4 and a sequence of { 2.0, 8.0, 12.0, 10.0, 6.0, 4.0, 14.0 }, the result of this function is { 8.0, 9.0, 8.0, 8.5 }.
8 people like thisPosted: 14 years ago by Brett V. Forsgren
-
2 people like thisPosted: 14 years ago by Daniel Robinson
Simple Silverlight Calculator UI interactive sample runnable inside http://tryfsharp.org.
0 people like thisPosted: 14 years ago by Phillip Trelford
Simple Silverlight Calculator UI interactive sample runnable inside http://tryfsharp.org.
1 people like thisPosted: 14 years ago by Phillip Trelford
Simple formula calculator including dynamic unit of measure support. Run as a script in Try F#, and try formula with units like 3m * 3m.
0 people like thisPosted: 14 years ago by Phillip Trelford
Several WinForms controls, like TreeView and ListView, implement methods BeginUpdate and EndUpdate, which suspend repainting of the control while items are being individually added to a control, preventing flicker caused by rapid repainting. But using BeginUpdate and EndUpdate is very imperative, and opens up the possibility for bugs, such as neglecting to call the matching EndUpdate. An obvious improvement would be to create an extension method on types implementing this pattern which takes a unit -> unit lambda which is executed between update pairs. But the pattern is only conventional, rather than through a common base class or interface. Hence this presents a reasonable opportunity to use F#'s statically resolved structural type system to implement a function which only works on Control types with the correct structural signature.
3 people like thisPosted: 14 years ago by Stephen Swensen
Triple version of Seq.pairwise.
2 people like thisPosted: 14 years ago by ptan
Select n elements in group from seq
2 people like thisPosted: 14 years ago by Ankur Dhama
Create Open XML Word document using the open XML SDK
3 people like thisPosted: 14 years ago by Piet Amersfoort
Create Open XML Spreadsheet using the open XML SDK
2 people like thisPosted: 14 years ago by Piet Amersfoort
A different approach to conditional debug functions
1 people like thisPosted: 14 years ago by David Klein
Functional quicksort inspired by the Haskell Quick Sort at http://www.haskell.org/haskellwiki/Introduction. Since F# lists aren't lazy, uses sequences instead of lists to be haskell like. Roughly O(n) if you Seq.take 1, full on QS if you enumerate the whole thing.
3 people like thisPosted: 14 years ago by Tony Lee
Parts of a little DSL to create WPF DataTemplate's in F#. Don't even want to think about the length of a corresponding C#. The F# code corresponds 1-to-1 to the visual tree constructed for the template.
8 people like thisPosted: 14 years ago by Cetin Sert
Async File Crawl
9 people like thisPosted: 14 years ago by fholm
State machine example, from Martin Fowler's Domain-Specific Languages book, implemented as an External DSL parser in F#. A set of mutually recursive functions are used to parse the string tokens and build the State Machine as an F# record type.
12 people like thisPosted: 14 years ago by Phillip Trelford
A FuncList is a "list-like" datatype with constant time append (represented as a function of cons-lists). The implementation is based on a convenient computation builder.
1 people like thisPosted: 14 years ago by Nick Palladinos
Create a Open Xml word document from a string array. In this snippet I did not reference the Open Xml SDK
1 people like thisPosted: 14 years ago by Piet Amersfoort
Silverlight default architecture is Model-View-ViewModel. This code gives full design time support for Microsoft Expression Blend. The F# ViewModel is seen as strongly typed data source in the Blend UI. There are two properties binded to the view: HiLabel (OneWay data binding) and MyName (TwoWay data binding). ViewModel implements the INotifyPropertyChanged to support the binding. The view project (HelloApp) is made with Blend (by designers) and it is Silverlight 5.0 project. The view codebehind is c# file and it has only this.DataContext -assignment. The viewmodel project (HelloApp.ViewModel) is F# Silverlight 4.0 library. It is made with VS2010 and F# (by developers). It contains the logical functionality of the current view.
5 people like thisPosted: 14 years ago by Tuomas Hietanen
Generates a sequence using a sequence generator and Async.StartWithContinuations. This is an attempt at modeling the OWIN delegate structure in F#
6 people like thisPosted: 14 years ago by Ryan Riley
A CPS version of FuncList, in order to avoid blowing the stack.
3 people like thisPosted: 14 years ago by Nick Palladinos
Agent that can be used for controlling the number of concurrently executing asynchronous workflows. The agent runs a specified number of operations concurrently and queues remaining pending requests. The queued work items are started as soon as one of the previous items completes.
21 people like thisPosted: 14 years ago by Tomas Petricek
The ReplaySubject
Posted: 14 years ago by Phillip Trelford
The snippet overrides default AsyncControllerActionInvoker so F# async workflows can be used for ASP.NET MVC 3. It declares a new base class for asynchronous controller. Controller method has to have return type Async
Posted: 14 years ago by Dmitry Morozov
Convert string to and from character lists.
11 people like thisPosted: 14 years ago by petebu
An active pattern for comparing two objects of the same type and implementing IComparable. Modeled on Standard ML comparison.
4 people like thisPosted: 14 years ago by petebu
This active pattern allows you to specify default values for option arguments in the signature of your function, so you can remove unnecessary calls to defaultArg. It also save you having to define a new name for the defaulted value.
22 people like thisPosted: 14 years ago by Kurt Schelfthout
You can use this code to make a async WebRequest from Silverlight to update ViewModel.
5 people like thisPosted: 14 years ago by Tuomas Hietanen
Implementation of Mutable Weighted Quick-Union with Path Compression in F#
5 people like thisPosted: 14 years ago by Rick Minerich
This snippet can be used to read all records from a given table and expose them as an IEnumerable
Posted: 14 years ago by Eduardo Claudio
Create a Open Xml spreadsheet fromxml. In this snippet I did not reference the Open Xml SDK
5 people like thisPosted: 14 years ago by Piet Amersfoort
Returns subsets of strings which match a specified prefix. The prefix is built incrementally by repeatedly calling a search function.
1 people like thisPosted: 14 years ago by Johann Deneux
This is a simple implementation of an object pool using an agent (MailboxProcessor). The pool is created with an initial number of object using the specified generator. The ObjectPool has three functions: Put: An item can be 'Put' into the pool. Get: An item can be taken from the pool ToListAndClear: A list of all the items in the pool is returned and the pool is cleared.
9 people like thisPosted: 14 years ago by 7sharp9
A simplistic discount curve bootstrapping process
14 people like thisPosted: 14 years ago by Wayne Bradney
for zec_ on irc
0 people like thisPosted: 14 years ago by fholm
Simple RichTextBox SQL highlighting with win32 LockWindowUpdate DllImport
7 people like thisPosted: 14 years ago by nCdy
It seems that you can't pass anonymous functions as parameters to active patterns.
3 people like thisPosted: 14 years ago by Kurt Schelfthout
escaping string, very terse . Update: a bit more terse, and perf improvement by using .ToCharArray() and Array.iter
1 people like thisPosted: 14 years ago by hammett
Simple string escaping.
5 people like thisPosted: 14 years ago by fzandona
Saw a Moving Average example on this site ( http://fssnip.net/4S ) and wondered if it could be done in even fewer lines of code. It can. This is why I love F#!
6 people like thisPosted: 14 years ago by Paul Papathomas
A function implemented using sequence expressions that returns all subsets of a specified set. The function is not optimized, but it is very easy to understand.
11 people like thisPosted: 14 years ago by Tomas Petricek
Similar to an async { } block but captures the result for future consumption. This structure can be very useful for performing multiple result-returning operations in parallel when the results aren't needed immediately. For example, performing several read/transform operations or pre-populating a cache with yet-to-be computed values. Microsoft's Task Parallel Library in .NET 4.0 includes a Future implementation so this version is only needed on earlier .NET versions. Comments, suggestions, and improvements are always welcome.
4 people like thisPosted: 14 years ago by Jason McCampbell
Seq.sumBy implemented in terms of Seq.fold
2 people like thisPosted: 14 years ago by ildjarn
F# Future using lazy and a threading event. Supports creating futures from functions or asyncs. Eager evaluation of can be specified.
4 people like thisPosted: 14 years ago by Ankur Dhama
Playable Tetris mini-game. Use arrow keys to move left and right and up to rotate, down to drop. Try it out in the browser on TryFSharp.org
18 people like thisPosted: 14 years ago by Phillip Trelford
A combinator based DSL for composing type-safe parameterized sql queries. Inspired by Olivier Danvy's "Functional Unparsing" paper.
10 people like thisPosted: 14 years ago by Nick Palladinos
Repeatedly call a function until it returns a positive result. Implemented using sequences.
3 people like thisPosted: 14 years ago by Johann Deneux
Detects a mouse down then up event without a move.
4 people like thisPosted: 14 years ago by Phillip Trelford
Detects a mouse down then up event without a move.
4 people like thisPosted: 14 years ago by Zach Bray
Ruby like map declaration syntax
6 people like thisPosted: 14 years ago by Saagar Ahluwalia
Example of a WPF/Silverlight Value Converter base class and concrete implementation.
6 people like thisPosted: 14 years ago by Tao Liu and Daniel Mohl
Sometimes you might wish to memoize a function whose input doesn't have the equality and comparison constraints, or maybe the comparison of your given type is just too slow for what you need. To fix this, you simply provide a function which converts the input into something more fitting as an extra parameter.
7 people like thisPosted: 14 years ago by Rick Minerich
The snippet implements a wrapper for standard F# agent that can be cancelled using the IDisposable interface. This makes it possible to use the agent locally (e.g. inside asynchronous workflow). When it is no longer needed, the agent's body is cancelled.
11 people like thisPosted: 14 years ago by Tomas Petricek
Tennis scoring system (at the game level). Includes some pattern-matching examples including 'when' guards.
4 people like thisPosted: 14 years ago by Kit Eason
I made LazyBuilder. The synthesis of the lazy function is troublesome. When the call of the Force() method increases, it is ugly. This solves the problem.
11 people like thisPosted: 14 years ago by zecl
this snippet presents a way to create macros in F# to automato VS IDE environment. To compile, just open a Command prompt window and type: fsc --out:fsmacros.dll --reference:envdte.dll --target:library fsmacros.fs Where FSMACROS.FS is the file name I gave for the code. After compile, copy the dll to C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\PublicAssemblies To use, just open F# interactive in Visual Studio (CTRL+ALT+F) and type: #r “envdte”;; #r “fsmacros”;; Let dte = vs10macros.getDte “The main window title appearing in you VS 2010”;;
1 people like thisPosted: 14 years ago by Eduardo Claudio
Interface workaround for circular dependency problem
5 people like thisPosted: 14 years ago by fholm
An agent based scheduler, can be sent a single schedule message (ScheduleOnce) and multiple schedule message (Schedule). The schedule messages comprise of a function to receive the message, the message, an initial TimeSpan before the message is scheduled, and another timespan for the schedule repeat. Check out my blog below for more details: http://bit.ly/mK4prb
9 people like thisPosted: 14 years ago by 7sharp9
This snippet extends several types from the System.Net namespace. It provides an easy to use API for creating asynchronous (as well as synchronous) HTTP servers using F# asynchronous workflows.
4 people like thisPosted: 14 years ago by Tomas Petricek
This snippet shows the implementation of three HTTP proxy servers in F#. The first is written using simple synchronous style (that isn't scalable). The second version uses event-based approach in the Node.js style, but is difficult to write. The third version uses F# async workflows and is both scalable and easy to write.
7 people like thisPosted: 14 years ago by Tomas Petricek
This snippet shows two improvements to asynchronous HTTP proxy from: http://fssnip.net/6e. First extension is to process page in chunks (instead of downloading the entire content first). The second extension is to use simple agent-based in-memory cache for previously visited pages.
7 people like thisPosted: 14 years ago by Tomas Petricek
An iteratee based on https://john-millikin.com/software/enumerator/ and http://okmij.org/ftp/Haskell/Iteratee/IterateeIO-talk-notes.pdf
8 people like thisPosted: 14 years ago by Ryan Riley
Haskell-style IO in F#.
16 people like thisPosted: 14 years ago by igeta
Solve the one to nine puzzle with a utility function that handles the depth first search. First saw the puzzle here: http://msdn.microsoft.com/en-us/vcsharp/ee957404
0 people like thisPosted: 14 years ago by dave jones
Code to solve the N-Queens problem.
4 people like thisPosted: 14 years ago by dave jones
This is a response to a Google interview question that someone encountered. A friend of mine was recently hired there and I've heard some thrilling stories of their interview process. So every now and then, I plan to code up a response to one of the hoards of interview questions they have.
0 people like thisPosted: 14 years ago by Antwan "A-Dubb" Wimberly
This snippet introduces a further subtlety into the previous posting, whereby the intra-hour movement of the hour hand is captured.
0 people like thisPosted: 14 years ago by HP
Using the general solve function to solve Sudoku. The puzzle specific code was translated from Norvig's Sudoku code, but any errors are mine. Reuses code from fssnip.net/6m and fssnip.net/6n
0 people like thisPosted: 14 years ago by dave jones
Here's an attempt at the Erlang ring problem in F#.
1 people like thisPosted: 14 years ago by David Grenier
Type extensions for System.Activator which enable the retrieval of COM instances from the Running Object Table.
1 people like thisPosted: 14 years ago by Huw Simpson
Seq group continuous matching elements [1;1;1;2;2;2] will become [ [1;1;1] ; [2;2;2] ]
3 people like thisPosted: 14 years ago by Ankur Dhama
Implements binary serialization. The encoding supports all records, unions, numeric types, strings, rank-1 arrays, maps, sets, lists and dictionaries. Strings are interned for efficiency. The encoding also uses binary compression (GZIP).
9 people like thisPosted: 14 years ago by Anton Tayanovskyy
Raises an exception again after attempting to run one or more handlers. Any failures in the handlers will be put into a new AggregateExeption. If no additional errors are raised, the original exception will be re-raised with a preserved stack trace.
4 people like thisPosted: 14 years ago by Sebastian Good
Turtle graphics library implemented as an internal DSL, providing a very similar syntax to Logo, it is runnable inside TryFSharp.org.
10 people like thisPosted: 14 years ago by Phillip Trelford
Split sequences based on a predicate.
3 people like thisPosted: 14 years ago by Ankur Dhama
An initial attempt at creating a ByteString type based on the Haskell version.
4 people like thisPosted: 14 years ago by Ryan Riley
Permutation and Combination using ListBuilder.
16 people like thisPosted: 14 years ago by zecl
The snippet implements Async.Choice method that takes several workflows and creates a workflow, which returns the first result that was computed. After a workflow completes, remaining workflows are cancelled using the F# async cancellation mechanism. (The method doesn't handle exceptions.)
7 people like thisPosted: 14 years ago by Tomas Petricek
Splices a sequence into another sequence at a specified index n. Can replace the existing element at n or keep it.
3 people like thisPosted: 14 years ago by Henrik Ravn
An old solution of mine to Erik Lippert's Comma Quibbling challenge. I really like this snippet because it shows that with F# we can hack elegant but also fast code.
3 people like thisPosted: 14 years ago by Nick Palladinos
Algorithms for generating US Census and Daitch-Mokotoff soundex string(s) based on a text input. Soundex is a phonetic algorithm for indexing names by sound, as pronounced in English. The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling.
4 people like thisPosted: 14 years ago by Matt Wilson
Take value from a sequence only when it changes (based on a predicate). Ex: Seq [1;1;1;3;3;3;5;5;5] will result in [3;5]
1 people like thisPosted: 14 years ago by Ankur Dhama
A JoinList is a variation on the list type that offers a constant time append operation.
5 people like thisPosted: 14 years ago by Ryan Riley
The static representations, unlike the encoded System.Tuple<_,...,_> forms, of tuples do not have ItemX properties and therefore static structural constraints cannot be used to obtain the nth item of a tuple. Here we give a utility with overloads for obtaining the nth item of a tuple. However, type inference is undermined in the presence of overloads
3 people like thisPosted: 14 years ago by Stephen Swensen
Implements a type into which any other type can be embedded. Check out this link for a discussion: http://ocaml.janestreet.com/?q=node/18
8 people like thisPosted: 14 years ago by Ademar Gonzalez
Quick example of using drag-n-drop with WinForms.
4 people like thisPosted: 14 years ago by MichaelGG
The function has the same type as Seq.reduce. Instead of reducing elements from the left to the right, it splits the input into two halves, reduces each half separately and then aggregates the results using the given function. This means that the values are aggregated into a ballanced tree, which can save stack space.
2 people like thisPosted: 14 years ago by Tomas Petricek
Async is a very versatile structure, which has been used to compose CPU/IO bound computations. So it is very tempting to implement a MapReduce function based on Async and borrowing ideas from the theory of list homomorphisms.
7 people like thisPosted: 14 years ago by Nick Palladinos
Here's a function which takes a comparator function and two sequences, and returns tuples consisting of an item from each sequence, where the comparator function returns true for those two items. This is a small part of my wider project to generate guitar chord shapes. One of the requirements there is to take a list of 'wanted' notes for a chord, and a list of 'available' notes within a range of frets and to combine them into an actual set of frettings. That's what led to tryFindFirstPair and hence to findPairs.
1 people like thisPosted: 14 years ago by Kit Eason
Third cut of a guitar chord shape generator. Given a fretted instrument with a particular tuning (eg. 6 string guitar tuned EADGBE), the generator will produce the frettings necessary to play any specified chord. This is not done from a chord library, but algorithmically (hence should work with whacky tunings). This version doesn't fully respect the limitations of the human hand beyond specifying a maximum 'stretch' of a few frets, so some of the shapes generated would need a friend to help play them! This will be dealt with in a future version. This third version contains improved handling of differing tunings and instruments (eg. DADGAD; banjo) but still doesn't check for unplayable shapes.
8 people like thisPosted: 14 years ago by Kit Eason
An iteratee that uses continuation-passing style as an optimization. There is no more discriminated union, and the signature should feel familiar to those using Async.StartWithContinuations.
5 people like thisPosted: 14 years ago by Ryan Riley
This is an implementation of the Continuation monad using a type, taking an exception handler, and allowing for Call/CC. This specific implementation is mostly Matt Podwysocki's. I have a similar implementation using a purely functional, exception-handler-less version in FSharp.Monad. Until now, I haven't been able to resolve the callCC operator.
4 people like thisPosted: 14 years ago by Ryan Riley
Generic batch job processor using Mail box processor. Sending quit message using PostAndReply will ensure that all jobs are completed before returning. (Exception handling is responsibility of the job)
6 people like thisPosted: 14 years ago by Ankur Dhama
This snippet demonstrates programming using asynchronous sequences. It contains (hidden) implementation of AsyncSeq type and combinators for working with it. More importantly, it demonstrates how to use asynchronous sequences to implement a simple sequential on-demand crawler.
11 people like thisPosted: 14 years ago by Tomas Petricek
The following sample wants to make sure the person’s age is between 18 and 65, weight is no more than 200 and tall enough (>120).
85 people like thisPosted: 14 years ago by Tao Liu
implement the decorate pattern in F#. The decorate pattern is to add new featuures to an object at runtime.
36 people like thisPosted: 14 years ago by Tao Liu
Observer pattern in F#
34 people like thisPosted: 14 years ago by Tao Liu
Strategy pattern in F#
83 people like thisPosted: 14 years ago by Tao Liu
the interest rate is decided by the internal state: account balance
34 people like thisPosted: 14 years ago by Tao Liu
Invoke the methods from incompatible types
111 people like thisPosted: 14 years ago by Tao Liu
Command pattern for redo-undo scenario.
47 people like thisPosted: 14 years ago by Tao Liu
use composite pattern to construct a tree and visitor pattern to bring back the traverse result.
34 people like thisPosted: 14 years ago by Tao Liu
singleton pattern in F#
39 people like thisPosted: 14 years ago by Tao Liu
Factory pattern in F#
82 people like thisPosted: 14 years ago by Tao Liu
Rx CombineLatest for list of IObservable<'a> to IObservable<'a array>.
13 people like thisPosted: 14 years ago by Ankur Dhama
Proxy pattern is a class functioning as an interface to something else.
37 people like thisPosted: 14 years ago by Tao Liu
Clumsy LoopBuilder.It's mischievous trick.
6 people like thisPosted: 14 years ago by zecl
Euler #5 solution
4 people like thisPosted: 14 years ago by Michael Falanga
Unlike the previous chain of responsibility, this version use the pipeline to chain responsibilities.
105 people like thisPosted: 14 years ago by Tao Liu
Scrap Your Boilerplate with the help of F#. Based on the original paper by Ralf Laemmel and Simon Peyton Jones.
9 people like thisPosted: 14 years ago by Nick Palladinos
Basic prime number generator
3 people like thisPosted: 14 years ago by d95danb
Simple check if a number is prime. See also http://fssnip.net/2w.
3 people like thisPosted: 14 years ago by d95danb
Calculate's when a the nth XKCD will appear, starting from XKCD 946. For a full explanation this snippet see: http://strangelights.com/blog/archive/2011/09/02/calculating-when-the-1000th-xkcd-will-appear.aspx
3 people like thisPosted: 14 years ago by Robert Pickering
An implementation of Coroutine by using a continuation monad. It's using a monad library [1]. [1] https://github.com/fsharp/fsharpx
7 people like thisPosted: 14 years ago by einblicker
Strassen's Multiplication Algorithm works much better than the standard approach when the matrix is large. The program implements a parallel version of it.
3 people like thisPosted: 14 years ago by Zhuobo Feng
A circular queue implemented over an array.
4 people like thisPosted: 14 years ago by Johann Deneux
Oleg's delimited continuation monad [1] and creating an external iterator from an internal iterator using it. [1] http://okmij.org/ftp/continuations/implementations.html#genuine-shift
7 people like thisPosted: 14 years ago by einblicker
version 1 is http://fssnip.net/62. This new version support convert from any existing function to a converter function by using composition and pipeline. The convert function is to make the function signature agree to the IValueConverter interface. You can add new functions in the FunctionLibrary module and reuse the class definition to reduce the coding effort. The first sample is to show how to make the converter pipeline work, the second one is a debugger converter used to debug the data binding problem.
91 people like thisPosted: 14 years ago by Tao Liu
This command redo-undo implement group the command under Do/Undo category.
71 people like thisPosted: 14 years ago by Tao Liu
An implementation of call-with-current-continuation for Async.
2 people like thisPosted: 14 years ago by Ryan Riley
This program is written in only 99 lines of actual code and remains enough readability. I used few short-coding technics. 1. no XAML. 2. pre-calculate every useful data for the purpose of eliminating useless states 3. using record type with set property as an alternative of view-model 4. initialize everything in one place. 5. encapsulate all states in one place.
17 people like thisPosted: 14 years ago by nagat01
The snippet uses asynchronous sequences (from F# AsyncExtensions) to download historical stock data from Yahoo. Data is downloaded in a buffered way on demand (as needed) and returned line by line. The sample then prints OHLC values for first 30 items.
6 people like thisPosted: 14 years ago by Tomas Petricek
Implements a simple Async.StartDisposable extension that can be used to easily create IObservable values from F# asynchronous workflows. The method starts an asynchronous workflow and returns IDisposable that cancels the workflow when disposed.
4 people like thisPosted: 14 years ago by Tomas Petricek
Implements the Observable.windowed function that creates an observable returning a sliding window. The function is an observable version of Seq.observable. The implementation uses a simple F# agent that keeps partial windows and sends them to an observer.
7 people like thisPosted: 14 years ago by Tomas Petricek
This code snippet enables the retrieval of the entity (Module or F# Type) in which the calling code is executing. This can be used to find the module or type name.
2 people like thisPosted: 14 years ago by Huw Simpson
Return a list of the prime factors for a natural number using trial division and a prime sieve. Ref: http://en.wikipedia.org/wiki/Trial_division Ref: http://fssnip.net/7D
0 people like thisPosted: 14 years ago by d95danb
Return a list of the prime factors for a natural number using trial division and a prime sieve. Ref: http://en.wikipedia.org/wiki/Trial_division Ref: http://fssnip.net/7D
0 people like thisPosted: 14 years ago by d95danb
Pack consecutive duplicates of list elements into sublists.If a list contains repeated elements they should be placed in separate sublists.
0 people like thisPosted: 14 years ago by Naveen
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?
3 people like thisPosted: 14 years ago by Gene Belitski
In England the currency is made up of pound, £, and pence, p, and there are eight coins in general circulation: 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p). It is possible to make £2 in the following way: 1x£1 + 1x50p + 2x20p + 1x5p + 1x2p + 3x1p How many different ways can £2 be made using any number of coins?
3 people like thisPosted: 14 years ago by Gene Belitski
While thinking on Project Euler Problem 40 solution (http://projecteuler.net/index.php?section=problems&id=40) the following subproblem has surfaced: how to glue up string presentations of a sequence members to reach a given length of result string. The snippet gives at least 3 different implementations of such function with performance comparison; as a bonus a solution to Problem 40 is given.
2 people like thisPosted: 14 years ago by Gene Belitski
Function that parses a Roman-numeral string and return the number it represents.
3 people like thisPosted: 14 years ago by Naveen
Calculates sha256 of the files passed in on the command line. Usage: fsi sha256.fsx downloadedFile.zip
2 people like thisPosted: 14 years ago by Tony Lee
The snippet shows a parser for command-line arguments supporting value lists for single commands. Calling with the following arguments: "Arg 1" "Arg 2" -test "Case 1" "Case 2" -show -skip "tag" produces the following map: map [("", seq ["Arg 1"; "Arg 2"]); ("show", seq []); ("skip", seq ["tag"]);("test", seq ["Case 1"; "Case 2"])] which can be used to find what data have been sent along with different commands. Calling with the following: "Arg 1" "Arg 2" /test="Case 1" "Case 2" --show /skip:tag produces the same result.
6 people like thisPosted: 14 years ago by Gennady Loskutov
Just a pendant to Naveen's readromannumerals; takes an int and produces a roman numeral string
4 people like thisPosted: 14 years ago by Jonas Avelin
This snippet implements a Clojure-like lambda function syntax using Code Quotations. However, this implementation is slow and, moreover, not type-safe. So I'm looking for a way to solve the issues.
6 people like thisPosted: 14 years ago by einblicker
Implements a bijective mapping between permutations and pairs of standard Young tableaux, both having the same shape. http://en.wikipedia.org/wiki/Robinson%E2%80%93Schensted_correspondence
4 people like thisPosted: 14 years ago by Ademar Gonzalez
Twitter now provides a streaming API which can be used to obtain a continuous stream of tweets on any set of topics, locations, etc., in real time. Read the full details here. It would be nice to convert this stream into an F# sequence so that it can be treated just as any other sequence if F#. This provides “composability”; separation of the generation of a sequence from its consumption. Here is a snippet that does that.
12 people like thisPosted: 14 years ago by Faisal Waris
A Monad for composing computations with retry logic. (Useful when we work with Cloud Services)
6 people like thisPosted: 14 years ago by Nick Palladinos
This program reads all *.csproj-files from a path and then uses Linq2Xml to show data about the projects. This should be a good template for scripts to manage tons of c#-project files. F# and LINQ-to-XML is very powerful combination.
9 people like thisPosted: 14 years ago by Tuomas Hietanen
Simple times table console based game.
3 people like thisPosted: 14 years ago by Phillip Trelford
Find the longest consecutive sub-sequence of increasing numbers.
0 people like thisPosted: 14 years ago by Naveen
Non-deterministic choice operation for F# asynchronous workflows - creates a workflow that returns the result of one of two asynchronous workflows, depending on which completes first. (The other workflow is not cancelled.)
4 people like thisPosted: 14 years ago by Tomas Petricek
JSON Parser using Regular Expressions & Active Patterns (just for fun).
9 people like thisPosted: 14 years ago by Phillip Trelford
simple CRC16
5 people like thisPosted: 14 years ago by nCdy
Regex String and Int, e g : "qwe123" -> "qwe" and 123, "qwe" -> "qwe", 123 -> 123
4 people like thisPosted: 14 years ago by nCdy
When we need lazy evaluation, we use the Lazy<'T>. However, the Lazy<'T> must evaluate explicitly. This example enables implicit evaluation(call-by-need).
6 people like thisPosted: 14 years ago by Nobuhisa
Subject is a class that implements both IObservable<'T> and IObserver<'T>
6 people like thisPosted: 14 years ago by Tuomas Hietanen
Basic thread-safe timed-expiry cache, implemented as a MailboxProcessor.
5 people like thisPosted: 14 years ago by Yusuf Motara
Written against CruiseControl.NET v1.5. Queries a CruiseControl.NET server for a project list and then computes min, max, average, and standard deviation of the build durations based on the statistics.csv CC.NET maintains.
3 people like thisPosted: 14 years ago by Matt Wilson
ipv4 conversion snippet, updated based on current version, changed a lot to make it a bit more .NETish
6 people like thisPosted: 14 years ago by david klein
The name is a bit trying, but the overall callback approach greatly simplifies the mechanism for calling and handling the System.Net.Sockets.Socket Async methods.
0 people like thisPosted: 14 years ago by Ryan Riley
PI number calculation based on the wikipedia page(http://en.wikipedia.org/wiki/Pi#cite_note-59). I used Newton's , Machine's and Ramanujan's formula. (updated: line 21: Seq.take => Seq.truncate)
4 people like thisPosted: 14 years ago by nagat01
A prime Eratosthenes' sieve, using a bit array and sieving only odd composites to conserve memory and keep things fast.
4 people like thisPosted: 14 years ago by Arjen Kopinga
Let's have some fun with higher order functions and instead of folding over a list, fold over the prime factors of a number. It can be optimized further by dividing out real primes instead of numbers of the form 6k+/-1, but it's not embarrassingly slow.
2 people like thisPosted: 14 years ago by Arjen Kopinga
The snippet shows how to implement reusable memoization function and how to use it to implement efficient Fibonacci number generator using dynamic programming.
6 people like thisPosted: 14 years ago by Tomas Petricek
Simple game of tennis... refactored after reading Richard Minerich blog post @http://richardminerich.com/2011/02/the-road-to-functional-programming-in-f-from-imperative-to-computation-expressions/
3 people like thisPosted: 14 years ago by Colin Bull
Another solution to the Tennis Kata, to score a tennis game.
10 people like thisPosted: 14 years ago by Don Syme
Simple Parser Monad implementation based on the paper "Monadic Parsing in Haskel" by Graham Hutton and Erik Meijer. Code discussion available here: http://blogs.msdn.com/b/fzandona/archive/2011/10/17/parsing-json-the-fun-way-monadic-parsers-records-and-type-providers-part-2.aspx
6 people like thisPosted: 14 years ago by fzandona
Simple JSON parser implemented using the Parser Monad. Code discussion here: http://blogs.msdn.com/b/fzandona/archive/2011/11/02/parsing-json-the-fun-way-json-parser-monad-part-3.aspx
4 people like thisPosted: 14 years ago by fzandona
It's a joke one liner implementation of Tennis Kata.Please see this code not seriously.
1 people like thisPosted: 14 years ago by nagat01
Agent that keeps a cache of web pages that were downloaded previously. The agent handles messages to add and get data as well as message to clear the cache.
7 people like thisPosted: 14 years ago by Tomas Petricek
Copy an array into a new one, changing the value at index 42 to 123. Uses "function" and pattern patching.
1 people like thisPosted: 14 years ago by Johann Deneux
The dining philosophers problem implemented using a waiter.
6 people like thisPosted: 14 years ago by Alex Muscar
This small script converts continuous 4 spaces to 2 spaces by using Regex. It gets the source code from a clip board text and save it to clip board. Since this program doesn't parse the source code, conversion is not perfect. But writing script which interacts with clipboard is so easy, you can automate your trivial coding work with a small effort. Using F#interactive with Clipboard is my favorite way of meta-programming.
3 people like thisPosted: 14 years ago by nagat01
This snippet is basically the same as http://fssnip.net/6A, except that the element whose predicate holds ends the previous group and the element after it starts a new one. Those two snippets (Seq.groupWhen, Seq.groupAfter) would be generally equivalent to the Haskell functions 'breakBefore' and 'breakAfter' from Data.List.Grouping.
0 people like thisPosted: 14 years ago by Thorsten Meinecke
Concatenates two strings together: ML or OCaml style
2 people like thisPosted: 14 years ago by Cameron Frederick
Simple calculator application for adding numbers, compiles to JavaScript via Pit (v0.1) (http://pitfw.posterous.com). Run: http://trelford.com/PitCalculatorApp.htm
3 people like thisPosted: 14 years ago by Phillip Trelford
Simplest possible sample code for accessing an in-process SQLite database file using LINQ The code does not use a dbml file for the mapping, but an attribute enriched type. (F# script, .Net 4.0, F# 2.0)
6 people like thisPosted: 14 years ago by Dirk Devriendt
This snippet implements a semi-coroutine by continuations.
4 people like thisPosted: 14 years ago by einblicker
Template pattern is a behavior-based pattern. Realized the importance of high order function, this is a way to use high order function. Still keep the type structure to organize my code.
38 people like thisPosted: 14 years ago by Tao Liu
Computation builder for writing non-deterministic computations.
8 people like thisPosted: 14 years ago by Tomas Petricek
Datetime Readable for Humans, Ported from Clojure https://github.com/pmn/noir-messageboard/blob/master/src/noir_messageboard/utils/utils.clj
25 people like thisPosted: 14 years ago by christophd
Using World Bank type provider and FSharpChart to show average university enrollment in Czech Republic, European Union and OECD members.
6 people like thisPosted: 14 years ago by Tomas Petricek
Simple times table browser based game., compiles to JavaScript via Pit (v0.1) (http://pitfw.posterous.com). Run: http://trelford.com/SevenSixes.htm
2 people like thisPosted: 14 years ago by Phillip Trelford
Minimal Inversion of Control (IoC) Container for Dependency Injection (DI) in under 100 lines of code. Implements the 3 Rs of DI: Register, Resolve, Release. Note: missing thread safety and fluent interface.
13 people like thisPosted: 14 years ago by Phillip Trelford
Bi directional map to implement toString and fromString function for descriminated unions.
4 people like thisPosted: 14 years ago by nagat01
General toString and fromString for discriminated unions using FSharp.Reflection
46 people like thisPosted: 14 years ago by Jonas Avelin
Function composition can be done by using >> operator. The snippet at http://fssnip.net/S is a wonderful sample. But that version generates a function which is not easy when you want to debug. This version is to use pipeline (|>) operator.
27 people like thisPosted: 14 years ago by Tao Liu
I started to write pure F# + WPF application in about half a year ago. Today, I found a good way to compose WPF controls with dependent values. It's only writing a dependency object type as a class and give it to constructors of GUI controls. In this snippet "Volume","ColorVolume" and "ShapeContainer" has no properties. But works as a View which represents internal Model and allows users to change internal data. You only need calling a constructor of them. It means that you can compose GUI controls and it's functionality as a immutable data structure. (Update 2011/12/02 8:33:00(UTC+09:00) : Removed some user defined operators and renamed a type similar to DependencyObject in this snippet Reactor to SharedValue.) (Update 2011/12/02 9:04:01(UTC+09:00) : renamed some variables..)
22 people like thisPosted: 14 years ago by nagat01
Higher order function 'withOutStr' to fork console output to a string. The function temporarily redirects Console.Out to a custom TextWriter
5 people like thisPosted: 14 years ago by Jonas Avelin
Code to drive a serial port. Trivial application to read a paper tape to a file from a GNT4604 paper tape reader attached to serial port COM3:
7 people like thisPosted: 14 years ago by Andrew Herbert
A function to calculate 'mixed numbers' - eg. 1 1/8. (With fix to reduce the fractional part to its lowest terms)
2 people like thisPosted: 14 years ago by Kit Eason
A quick-and-dirty editor for discriminated unions in a property grid. I use this for editing trees of F# records and unions. Note that any records must have a "Default" static property which returns a default instance.
3 people like thisPosted: 14 years ago by Rick Minerich
Polyvariadic fixpoint combinator in F# (heavily inspired by Haskell)
3 people like thisPosted: 14 years ago by Nick Palladinos
Simple DSL for describing cups of Starbucks coffee and computing prices (in dollars).
16 people like thisPosted: 14 years ago by Phillip Trelford
A light domain specific language for declaring xml in F# as code.
9 people like thisPosted: 14 years ago by Huw Simpson
A couple of operators for 'between, inclusive' and 'between, exclusive'.
10 people like thisPosted: 14 years ago by Kit Eason
Simple domain-specific language (DSL) for describing financial contracts in F#. A contract is represented using a discriminated union. Evaluating a contract gives the orders that may happen at a given date.
8 people like thisPosted: 14 years ago by Tomas Petricek
A simple active pattern that allows you to match WebExceptions by HttpStatusCode. I find it useful for quick scripts where I only need WebClient and don't have to get involved with WebRequest etc.
12 people like thisPosted: 14 years ago by Leaf Garland
I learned how to implement this by reading this great good project http://code.google.com/p/fsharp-typeclasses/ But I can't understand why the project needs ternary operator. I used binary operator and seems it's okay.
6 people like thisPosted: 14 years ago by nagat01
A function that takes a random subset from a seq<'T>.
1 people like thisPosted: 14 years ago by Taha Hachana
Some simple functions to tidy up text and quote it, so that it's suitable to go into a CSV.
0 people like thisPosted: 14 years ago by Kit Eason
Some simple functions to tidy up text and quote it, so that it's suitable to go into a CSV.
3 people like thisPosted: 14 years ago by Kit Eason
Simple Async Observable Subject<'T> based on MailboxProcessor. Type declaration is more ML like, but the idea is represented in a simple way!
6 people like thisPosted: 14 years ago by Fahad
Converts an Enum to a Selectlist which can be used by a @Html.DropDownList
12 people like thisPosted: 14 years ago by christophd
A vector type with units of measure built on top of XNA's Vector3. Not complete, the point is mainly to show how to use generic units of measure to adapt an existing type.
9 people like thisPosted: 14 years ago by Johann Deneux
A typical problem when working with arrays and indices is that it's easy to access an array with the wrong index. Units of measure in F# can be applied to integers, which makes it possible to abuse them to prevent this kind of error.
7 people like thisPosted: 14 years ago by Johann Deneux
Take some text and work out where the left margins are, returning the most common margin settings first. Useful for processing somewhat messy text items like movie scripts. Left margins are defined by leading spaces. Tabs must be expanded before calling.
3 people like thisPosted: 14 years ago by Kit Eason
This is an implementation of the famous 'magic number' method of rapidly calculating (inverse) square roots. (See http://en.wikipedia.org/wiki/Fast_inverse_square_root.) In practice, this version is no faster in F# than using 1./sqrt(x). I've posted it as an example of how you can get down-and-dirty with the bits in F# if you need to.
7 people like thisPosted: 14 years ago by Kit Eason
This script opens a window with a red rectangle which is moved by dragging. I like writing interactive GUI without MVVM, FRP and Markup language.
8 people like thisPosted: 14 years ago by nagat01
Shuffles a deck of cards, deals 2 hands applying punto banco rules before declaring a winner or a tie.
4 people like thisPosted: 14 years ago by Phillip Trelford
10 line Point of Sale (POS) application takes barcodes from a USB barcode scanner or keyboard adding matching products. Entering an empty string completes the action and gives the total.
7 people like thisPosted: 14 years ago by Phillip Trelford
OCaml original here : http://eigenclass.org/R2/writings/heterogeneous-containers-in-ocaml
9 people like thisPosted: 14 years ago by Ademar Gonzalez
The snippet shows a simple F# agent that calculates average from the received values. It supports one message for adding numbers to the statistics and one for resetting the state. Moreover, the agent limits the processing rate to 1 message per second.
6 people like thisPosted: 14 years ago by Tomas Petricek
Sometimes it is extremely useful to check some calculations with Excel. The snippet shows how F# expressions can be transformed into Excel formulae. The data is exported together with the formulae, e.g. a, b and sum function as input sets A1's value to a, B1's to b and C1's formula to "=$A$1+$B$1"
17 people like thisPosted: 14 years ago by Natallie Baikevich
Determining If You Are Running the Checked Build p.48 Windows Internals 5th Edition.
1 people like thisPosted: 14 years ago by David Klein
A pattern for creating n-ary Seq.map functions.
5 people like thisPosted: 14 years ago by Nick Palladinos
A pattern for creating n-ary Seq.map functions, based on numerals.
5 people like thisPosted: 14 years ago by Nick Palladinos
F# koodia async käsittelyyn
3 people like thisPosted: 14 years ago by Not important
Async & paraller
4 people like thisPosted: 14 years ago by Not important
A Small BrainFuck Interpretor (~50 lines). Probably not very efficient only started learning F# a few days ago.
8 people like thisPosted: 14 years ago by Adam Speight
This script facilitates to load all the .fs files in the specified F# project in correct compilation order.
5 people like thisPosted: 14 years ago by nagat01
A function that nests items of a sequence that do not match a specified predicate under the last item that matches the predicate. The input is a sequence of values and the result is a sequence of pairs where the second element is a list of nested items.
3 people like thisPosted: 14 years ago by Tomas Petricek
A quick and reconfigurable way to create system or hardware IDs based on WMI Win32 classes for software licensing or similar purposes. (Perhaps a perfect fit for type providers in F# 3.0!)
3 people like thisPosted: 14 years ago by Cetin Sert
The snippet shows how to send HTTP POST request to a web page and download the generated HTML result. The POST data is encoded as a byte array and written to the request stream of HttpWebRequest.
10 people like thisPosted: 14 years ago by Tomas Petricek
A Circular, or Ring, Buffer that flattens incoming arrays and allows consumers to take arbitrary-sized chunks. Improvements and suggestions welcome. Fork my gist at https://gist.github.com/1648579.
7 people like thisPosted: 14 years ago by Ryan Riley
Async.Parallel2 and Async.Parallel3, for running three Async's in parallel as thread pool tasks. Alternative versions given which use Async.Parallel under the hood.
18 people like thisPosted: 14 years ago by Don Syme
Minimalist assistant to read data / execute database command. //I have question //How to Print the read value i.e.Customer.Id and Customer.Name //some sample regarding are available?? //Link For convering c# code to f# would be helpful-reply me at
8 people like thisPosted: 14 years ago by S. Kasperovich
A pattern for programming with generic folds (catamorphisms). Based on the classic "Functional Programming with Bananas, Lenses, Envelopes and Barbed Wire" (1991) (Meijer, Fokkinga, Paterson).
8 people like thisPosted: 14 years ago by Nick Palladinos
Here we define Peano arithmetic using F# abstract data types.
5 people like thisPosted: 14 years ago by Daniil
Implementation of Async.Sleep in f# 2.0 doesn't allow break it execution until the time elapsed. Here is the alternate implementation which support immediate cancellation. According to discussion http://stackoverflow.com/questions/9041491/is-there-any-reason-why-async-sleep-can-not-be-canceled-immediately .
2 people like thisPosted: 14 years ago by Andrei Kolomentsev
An implementation of (part of) Peter Henderson's picture language from the SICP book.
4 people like thisPosted: 14 years ago by Jonas Avelin
The standard windows.forms text box supports auto-completion, but only for single-line text boxes. The code below can be used to add auto-completion against a fixed set of words to any text box that inherits from TextBoxBase.
5 people like thisPosted: 14 years ago by Johann Deneux
An operator to compare two curves by the sum-of-squares-of-differences method.
2 people like thisPosted: 14 years ago by Kit Eason
Compute the Discrete Fréchet Distance between two arrays (which may be of different lengths). Based on the 1994 algorithm by Thomas Eiter and Heikki Mannila. Not extensively tested, so use at your peril! (This version with some small fixes.)
0 people like thisPosted: 14 years ago by Kit Eason
These are F# solutions of Ninety-Nine Haskell Problems which are themselves translations of Ninety-Nine Lisp Problems and Ninety-Nine Prolog Problems. The solutions are hidden so you can try to solve them yourself.
34 people like thisPosted: 14 years ago by Cesar Mendoza
These are F# solutions of Ninety-Nine Haskell Problems which are themselves translations of Ninety-Nine Lisp Problems and Ninety-Nine Prolog Problems. The solutions are hidden so you can try to solve them yourself.
7 people like thisPosted: 14 years ago by Cesar Mendoza
These are F# solutions of Ninety-Nine Haskell Problems which are themselves translations of Ninety-Nine Lisp Problems and Ninety-Nine Prolog Problems. The solutions are hidden so you can try to solve them yourself.
6 people like thisPosted: 14 years ago by Cesar Mendoza
These are F# solutions of Ninety-Nine Haskell Problems which are themselves translations of Ninety-Nine Lisp Problems and Ninety-Nine Prolog Problems. The solutions are hidden so you can try to solve them yourself.
4 people like thisPosted: 14 years ago by Cesar Mendoza
These are F# solutions of Ninety-Nine Haskell Problems which are themselves translations of Ninety-Nine Lisp Problems and Ninety-Nine Prolog Problems. The solutions are hidden so you can try to solve them yourself.
6 people like thisPosted: 14 years ago by Cesar Mendoza
These are F# solutions of Ninety-Nine Haskell Problems which are themselves translations of Ninety-Nine Lisp Problems and Ninety-Nine Prolog Problems. The solutions are hidden so you can try to solve them yourself.
7 people like thisPosted: 14 years ago by Cesar Mendoza
These are F# solutions of Ninety-Nine Haskell Problems which are themselves translations of Ninety-Nine Lisp Problems and Ninety-Nine Prolog Problems. The solutions are hidden so you can try to solve them yourself.
3 people like thisPosted: 14 years ago by Cesar Mendoza
These are F# solutions of Ninety-Nine Haskell Problems which are themselves translations of Ninety-Nine Lisp Problems and Ninety-Nine Prolog Problems. The solutions are hidden so you can try to solve them yourself.
5 people like thisPosted: 14 years ago by Cesar Mendoza
These are F# solutions of Ninety-Nine Haskell Problems which are themselves translations of Ninety-Nine Lisp Problems and Ninety-Nine Prolog Problems. The solutions are hidden so you can try to solve them yourself.
10 people like thisPosted: 14 years ago by Cesar Mendoza
These are F# solutions of Ninety-Nine Haskell Problems which are themselves translations of Ninety-Nine Lisp Problems and Ninety-Nine Prolog Problems. The solutions are hidden so you can try to solve them yourself.
3 people like thisPosted: 14 years ago by Cesar Mendoza
These are F# solutions of Ninety-Nine Haskell Problems which are themselves translations of Ninety-Nine Lisp Problems and Ninety-Nine Prolog Problems. The solutions are hidden so you can try to solve them yourself.
5 people like thisPosted: 14 years ago by Cesar Mendoza
Simple md5 cracker, example of using permutations and pseq rather than cracking.
2 people like thisPosted: 14 years ago by david klein
Solving Ceasar shfit with frequency tables.
4 people like thisPosted: 14 years ago by David Klein
A script that consumes the Stackoverflow API in a dynamic fashion
7 people like thisPosted: 14 years ago by Mauricio Scheffer
Matrix
3 people like thisPosted: 14 years ago by Matrix
TicTacToe game simulator implemented by using Joinads(http://tomasp.net/blog/joinads-async-prog.aspx). Game logic in this snippet was simplified so nicely by using Joinads. You can run this snippet on Try Joinads (http://tryjoinads.org/).
4 people like thisPosted: 14 years ago by nagat01
Save the attachments of the first 10 mails to disk
1 people like thisPosted: 14 years ago by Joeri Belis
Team Foundation Server (TFS): Check Out a file.
3 people like thisPosted: 14 years ago by Tuomas Hietanen
example to use the open source .net FileHelpers library to read a CSV ( http://filehelpers.sourceforge.net/ ). csv example with no exception error field1,field2,field3 123,123,aaa 456,123,aaa example with exception where the functions returns an empty array field1,field2,field3 123,aaa,aaa 456,123,aaa
2 people like thisPosted: 14 years ago by Joeri Belis
Positions child elements in sequential position from left to right, breaking content to the next line at the edge of the containing box. Tryable at http://tryfsharp.org
3 people like thisPosted: 14 years ago by Phillip Trelford
Using FSharpChart control. Just call Charting.Plot() to chart series or collections of series. No need to create forms, etc.
2 people like thisPosted: 14 years ago by Boris Kogan
A simple and declarative solution based on Joinads.
5 people like thisPosted: 14 years ago by Nick Palladinos
Take a sequence and make it into a sequence of sequences, where the inner sequences are of a specified length. (The last inner sequence may be shorter.) Useful, for instance, for rending sequences into two-way HTML grids.
1 people like thisPosted: 14 years ago by Kit Eason
Take a sample of a specified length from a sequence. The sample is guaranteed to be of the requested size (unless there are too few elements in the original sequence). Sample items will be taken at equal intervals. (This version with some simplifications and tidy-ups.)
0 people like thisPosted: 14 years ago by Kit Eason
This program reads all *.csproj-files from a path and then uses Linq2Xml to show or modify data about the projects. This should be a good template for scripts to manage tons of c#-project files. F# and LINQ-to-XML is very powerful combination.
7 people like thisPosted: 14 years ago by Tuomas Hietanen
demonstrate how to use object expression to create a WPF/Silverlight command.
22 people like thisPosted: 14 years ago by Tao Liu
Simple n-gram algorithm implementation
Posted: 14 years ago by Daniil Frumin
How to avoid delegation boilerplate in inhertance heavy OOP code while maintaining proper accessibility like seen here https://github.com/fsharp/fsharp/blob/master/src/fsharp/FSharp.Core/seq.fs#L82 and mentioned in Expert F# 2.0 "Using Partially Implemented Types via Implementation Inheritance " Uses auto-properties that only work with F# 3.0
7 people like thisPosted: 14 years ago by Associat0r
A Turing machine emulator. An infinite tape is simulated by a zipper, instructions are stored in the binary tree for faster lookup.
4 people like thisPosted: 14 years ago by Daniil
Polymorphic (via generics) Maybe monad/computational expression with default value + Zipper
6 people like thisPosted: 14 years ago by Daniil
We all know about BOOBIES - but how many other dictionary words can you spell upside-down on a calculator?
2 people like thisPosted: 14 years ago by Kit Eason
Implementation of Langton's ant route.. Takes first 1000 steps and returns only black fields.
2 people like thisPosted: 14 years ago by stejcz
Implementation of Langton's ant route.. Takes first 1000 steps and returns only black fields.
4 people like thisPosted: 14 years ago by stejcz
Demo F# unit test in VS11 beta. In VS 2010 unit testing requires a hack whereby you add a c# test project to your solution and add to that project a linked item to the DLL of the F# project with the test methods.
6 people like thisPosted: 14 years ago by Jack Fox
Lab3
0 people like thisPosted: 14 years ago by Mikhail Dubov
I have been working on my "Functional Style" and like to think that I have improved a bit. The list order is no longer maintained in this snippet; however as the order change is simply a feature of the foldBack process the reversal of input and reversal of output is a reliable (and efficient?) fix.
4 people like thisPosted: 14 years ago by visProcessEngg
A simple implementation for the sieve of Eratosthenes.
3 people like thisPosted: 14 years ago by Gab_km
DSL for functional style, HUnit-like testing with MbUnit.
3 people like thisPosted: 14 years ago by Mauricio Scheffer
A simple way to count the non-blank, non-comment lines in your code. (Doesn't use project files to identify source; just a wildcard. Doesn't support multi-line comments.)
3 people like thisPosted: 14 years ago by Kit Eason
Powerset function followed by with tiny sample.
2 people like thisPosted: 14 years ago by notostraca
Just toying around with making my F# code a little smaller with Haskell operators
5 people like thisPosted: 14 years ago by Cameron Frederick
One of the problems with using FileSystemWatcher to detect new files and process them is that it tells you when the file starts being created, not when it finishes. Use this little function to poll the file until it stops being written to.
7 people like thisPosted: 14 years ago by Kit Eason
Draws a Sierpinski triangle using WPF
12 people like thisPosted: 14 years ago by Mathias Brandewinder
Retry monad: chaining functions together, retrying each one if exceptions are thrown, until the first time a function can no longer be retried
5 people like thisPosted: 14 years ago by Boris Kogan
Computes the Minimum Edit Distance or the Levenshtein Distance between two words
3 people like thisPosted: 14 years ago by Gustavo Guerra
A Lazy Xml structure for processing large xml documents.
11 people like thisPosted: 14 years ago by Nick Palladinos
There's an easy way to create JSon objects using Newtonsoft's Json.Net. The common problem with Json.Net is that there's usualy a lot of overhead when creating Json with it as there're a lot of 'new', parentheses, nested objects when we don't need them. And it becomes annoying quite fast. DU Json and toJson function allow to create Json tree and convert it to Json.Net JObject hierarchy. On the examples the usage of lightweight syntax doesn't give a lot of win but it will be more clearer when it come to more complicated objects.
8 people like thisPosted: 14 years ago by Dmitry Lobanov
Discriminated unions to represent a HTML file.(not completely)
3 people like thisPosted: 14 years ago by Gab_km
A while ago I posted a snippet to calculate the 'Discrete Fréchet Distance' between two curves. If we treat a word as a 'curve' by giving each letter an index (with similar-sounding letters having closer indices) we can compare words by the Fréchet distance between them! An alternative to edit-distance...
3 people like thisPosted: 14 years ago by Kit Eason
Compositional expression parsing with monads. https://bitbucket.org/ZachBray/parsad
9 people like thisPosted: 14 years ago by Zach Bray
Computes Levenshtein (min edit) distance between two strings http://en.wikipedia.org/wiki/Levenstein_Distance
9 people like thisPosted: 14 years ago by Lakret
reflection, not exactly efficient but good canvas to start exploring
5 people like thisPosted: 14 years ago by David Klein
It's fairly straightforward in-place QuickSort implementation which uses ThreadPool for parallelization. Still slower than library function Array.sortInPlace, though.
3 people like thisPosted: 14 years ago by Lakret
A single life annuity function in F# including supporting functions such as probability of survival, pure endowment and discounted interest rate calculation. I've gone for (what I believe to be) a more functional approach than the previous version. I've cobbled together a sort of computation expression type to facilitate transforming the AgeVector. The code below contains test data and sample tests so that you can see how it should be used. If you have any queries or advice about this please contact me on twitter @CdeRoiste . Have fun!
8 people like thisPosted: 14 years ago by Kevin Roche
JSON parsing with monads. See also "Expression parsing with monads" (http://fssnip.net/bi). Author URL: http://www.zbray.com
8 people like thisPosted: 14 years ago by Zach Bray
Creating an asynchronous HTTP Server in F#.
6 people like thisPosted: 14 years ago by Julian Kay
This code illustrates Bayes' Theorem in action on the Let's Make a Deal problem (aka Monty Hall Problem), which several authors have used to illustrate Bayes' Theorem. (It's easy to search the internet for further explanation.) Run with the audit option to audit up to the first 100 games. Running without audit is faster and can simulate a couple billion games.
5 people like thisPosted: 13 years ago by Jack Fox
Andrew's Monotone Chain Convex Hull algorithm: given points in 2 dimensions, determine their convex hull by constructing the upper and lower hull.
6 people like thisPosted: 13 years ago by Mathias Brandewinder
This is a simple implementation of a monadic transaction builder for Clojure-style atoms. Based on original code by Nick Palladinos.
15 people like thisPosted: 13 years ago by Eirik Tsarpalis
The snippet implements a function "expand" that takes a quotation and performs two operations. It replaces all calls to methods marked with ReflectedDefinition with the body of the method and it simplifies all expressions that can be reduced in call-by-name style (let binding & application of lambda).
7 people like thisPosted: 13 years ago by Tomas Petricek
When sprintf and String.concat is either too slow or not really what is needed, one can use System.Text.StringBuilder. This snippet makes working with StringBuilder much more convenient and the resulting code more succint.
1 people like thisPosted: 13 years ago by Bent Rasmussen
Domain model for the Tesco checkout implemented in F# using discriminated unions (in 20 lines of code) and console-based user interface for scanning products and calculating the total price.
5 people like thisPosted: 13 years ago by Tomas Petricek
The sample shows two different reprezentations of Tesco checkout. The first one stores scanned items - as a list of either purchase or cancel items - and the second stores final bill with product and total quantity. The snippet implements transformation that corresponds to finalizing the purchase.
3 people like thisPosted: 13 years ago by Tomas Petricek
You can use numeric literals, constant expressions and operator overloading to make your own arithmetics. Useful in DSL languages. With NumericLiterals, you can use any of Q, R, Z, I, N, G. Basic syntax: [Number][Letter] will forward the call to the type NumericLiteral[Letter] to FromInt32 [Number] (or FromInt64 or FromString...)
9 people like thisPosted: 13 years ago by Tuomas Hietanen
A small sample how to use F# 3.0 Entity Framework (EF) Type Provider. Visual Studio 11 Beta (and Northwind sample database) needed.
5 people like thisPosted: 13 years ago by Tuomas Hietanen
Some basic statistics functions in F#, including erfc, erfcinv, normcdf, normpdf, norminv, additiveCorrection, multiplicativeCorrection, a Box-Mueller RandomSampler and a unitized type for a Gaussian distribution. Based on Ralf Herbrich's samples at http://blogs.technet.com/b/apg/archive/2008/04/05/trueskill-through-time.aspx
5 people like thisPosted: 13 years ago by Robert Herman
Simple Computational expressions / monad / builder -example, using .NET Nullable as demo.
5 people like thisPosted: 13 years ago by Tuomas Hietanen
Setup Code for Online F# Koans
2 people like thisPosted: 13 years ago by Chris Marinos
An online version of the F# Koans for use with tryfsharp
13 people like thisPosted: 13 years ago by Chris Marinos
Simple domain-specific language for modeling of financial contracts.
8 people like thisPosted: 13 years ago by Tomas Petricek
Domain-specific language for detecting patterns in stock prices. Run using try F#.
5 people like thisPosted: 13 years ago by Tomas Petricek
Examples that use domain-specific langauge for detecting price patterns. To run the sample, load the previous snippet in TryF#. It opens the sample automatically.
2 people like thisPosted: 13 years ago by Tomas Petricek
Yet another ping pong sample with agents.
5 people like thisPosted: 13 years ago by Ryan Riley
Parameterizing pong allows us to do even more fun things. Here we use a few message types to allow stateful consumption of data sent by ping to its pongs.
3 people like thisPosted: 13 years ago by Ryan Riley
Inspired by this post: http://www.jasq.org/2/post/2012/05/inverse-fizzbuzz.html (fixed small typo, plus trying out this editing fssnip for the first time)
1 people like thisPosted: 13 years ago by Tony Abell
In mathematics, the Fibonacci numbers or Fibonacci series or Fibonacci sequence are the numbers in the following integer sequence: [0; 1; 1; 2; 3; 5; 8; 13; 21; 34; 55; 89; 144; 233; 377; ...] http://en.wikipedia.org/wiki/Fibonacci_number
5 people like thisPosted: 13 years ago by Tuomas Hietanen
A typecast free experiment in Generic Programming. Inspired by "Scrap Your Boilerplate (with class)".
8 people like thisPosted: 13 years ago by Nick Palladinos
A set of Async primitives as described by Dave Thomas [1] (and derived from Stephen Toub [2]). [1] http://moiraesoftware.com/blog/2012/04/22/back-to-the-primitive-ii/ [2] http://blogs.msdn.com/b/pfxteam/archive/2012/02/11/10266923.aspx
2 people like thisPosted: 13 years ago by Ryan Riley
Sometimes, we may run into this kind of situation that we want to check if the given method/function has been initialized. We all know this is fairly easy in C#, since we can use delegate to invoke the function , then verify if the value of delegate is null. But in F# , delegate is rarely needed because F# can treat a function as a value, without the need for any wrapper. So , here is an easy way to solve this problem.
6 people like thisPosted: 13 years ago by ZackZhou
This snippet automatically speeches text of question,answers and comments in a Stackoverflow article. It requires HtmlAgilityPack(available from Nuget package manager).(Attention: You need reset F# interactive to stop the speech)
6 people like thisPosted: 13 years ago by nagat01
A compositional type system built using generics and monads in F#. It is only a very limited, _toy_ project exploring traits, mixins and aspect-oriented programming.
17 people like thisPosted: 13 years ago by Zach Bray
Computes the nth value of a sequence if the nth value is past the length of the sequence then None is returned else some
3 people like thisPosted: 13 years ago by Colin Bull
Quick demo of using F# to interop with a native C library. C Library has not been checked for algorithm correctness (but works exactly as the origional).
13 people like thisPosted: 13 years ago by David Klein
Memoize a function in a thread-safe manner. Added a wrapper around the value a. The idea being, that a unit value is represented as a null value at run time and as such the concurrent dictionary throws.
11 people like thisPosted: 13 years ago by Matt Collins
Here is the implementation of the three types in WCF Azure, and a sample using WCF in worker role, a WPF test project to invoke the three kinds of data type from worker role. Link is http://fsharp3sample.codeplex.com/SourceControl/changeset/view/13876
4 people like thisPosted: 13 years ago by AndrewXue
A sample that translates simple F# quotations (method calls, property getters) to stnadard C# LINQ expression trees.
7 people like thisPosted: 13 years ago by Tomas Petricek
This wrapper will handle translating F# quotations into LINQ expressions that AutoMapper can use, enabling AutoMapper to be configured from F# code. You must reference AutoMapper and FSharp.PowerPack.Linq, or include Linq.fsi and Linq.fs from the PowerPack into your project.
10 people like thisPosted: 13 years ago by Joel Mueller
Zombie state machine code sample. Use arrow keys to move humanoid. Robots activate when in range of humanoids. Try it out in the browser with TryFSharp.org.
6 people like thisPosted: 13 years ago by Phillip Trelford
Solution to Minesweeper Kata challenge at Goto Copenhagen 2012 conference "Programming with the Stars" track.
4 people like thisPosted: 13 years ago by Phillip Trelford
Solution to Minesweeper Kata second challenge at Goto Copenhagen 2012 conference "Programming with the Stars" track. Runnable at http://tryfsharp.org.
2 people like thisPosted: 13 years ago by Phillip Trelford
Given a NuGet package name, this code will download the package, extract it to a temp directory, and return a sequence of FileInfo objects representing assemblies from that package, with a preference for .NET 4.5 and 4.0 assemblies, if present. Requires the "DotNetZip" package.
6 people like thisPosted: 13 years ago by Joel Mueller
Minesweeper computation Kata as a tweet (140 characters) not counting code to open namespace and to prepare field as a 2D array.
6 people like thisPosted: 13 years ago by Phillip Trelford
Any type signature has the form of a curried chain T0 -> T1 -> .... -> Tn, where Tn is not a function type. The codomain of a type is precisely Tn. This is a simple implementation that uses reflection to determine the codomain for arbitrary types.
4 people like thisPosted: 13 years ago by Eirik Tsarpalis
The Eurovision final scoring system using records and some higher order functions. (Results are fictional - no-one seems to publish the full voting live online.)
2 people like thisPosted: 13 years ago by Kit Eason
Small example illustrating how to use Arrays and Sequences to simulate simple Markov chain and evaluate their stationary distribution.
4 people like thisPosted: 13 years ago by Mathias Brandewinder
A minimal Brainfuck Interpreter (<30 lines) running Hello World!
6 people like thisPosted: 13 years ago by Phillip Trelford
An extension of MailboxProcessor that catches all unhandled exceptions (in the body of the mailbox processor) and reports them using an event. Otherwise, the public interface is the same as for MailboxProcessor.
5 people like thisPosted: 13 years ago by Tomas Petricek
Merges two sorted lists by a key.
4 people like thisPosted: 13 years ago by Simon Weijgers
Minimal Befunge-93 interpreter.
2 people like thisPosted: 13 years ago by Phillip Trelford
Entity Framework doesn't currently support async operations, but as long as the underlying provider is System.Data.SqlClient we can make it work.
3 people like thisPosted: 13 years ago by Joel Mueller
Implements simple library for downloading Yahoo stock prices and displaying charts in Try F#. This snippet loads another one with examples.
2 people like thisPosted: 13 years ago by Tomas Petricek
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).
1 people like thisPosted: 13 years ago by Tomas Petricek
Yet another tutorial based on the DSL for modelling financial contracts. This part just loads library for downloading prices & loads another snippet. Designed to run in Try F#.
0 people like thisPosted: 13 years ago by Tomas Petricek
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#.
0 people like thisPosted: 13 years ago by Tomas Petricek
Simple walkthrough that demonstrates how to estimate the value of PI using Monte Carlo simulation. A few holes need to be filled in and then you can run & parallelize the sample!
4 people like thisPosted: 13 years ago by Tomas Petricek
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.
4 people like thisPosted: 13 years ago by Eirik Tsarpalis
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. ;)
4 people like thisPosted: 13 years ago by Karsten P.
have a project to write some basics from gzip, needed crc32, seems fast enough, fixed one bug!
4 people like thisPosted: 13 years ago by David Klein
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.
2 people like thisPosted: 13 years ago by Kit Eason
An ASCII Mandelbrot visualisation. (Suggested by a tweet from Jon Harrop, but any bugs are mine.)
2 people like thisPosted: 13 years ago by Kit Eason
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
7 people like thisPosted: 13 years ago by Tomas Petricek
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.
4 people like thisPosted: 13 years ago by Tomas Petricek
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.
8 people like thisPosted: 13 years ago by Eirik Tsarpalis
Function to generate color values to reflect the relative intensity of numeric values in a range. --- Fixed edge case of when max=min
4 people like thisPosted: 13 years ago by Faisal Waris
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.
14 people like thisPosted: 13 years ago by Eirik Tsarpalis
Tiny robot simulate, it's available to run on tryfs.net (but not on iPad).
3 people like thisPosted: 13 years ago by a_a
seq to IEnumerator and IEnumerable
3 people like thisPosted: 13 years ago by Graham Spiers
Encoding mutually-recursive functions with a Polyvariadic fixpoint combinator.
5 people like thisPosted: 13 years ago by Nick Palladinos
Simple implementation of Conway's Game of Life for the TryF# web site.
0 people like thisPosted: 13 years ago by Tomas Petricek
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.
7 people like thisPosted: 13 years ago by Eirik Tsarpalis
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
6 people like thisPosted: 13 years ago by Mathias Brandewinder
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.
9 people like thisPosted: 13 years ago by Rick Minerich
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.
2 people like thisPosted: 13 years ago by Rick Minerich
Single level retro game playable inside TryFsharp using the cursor keys.
9 people like thisPosted: 13 years ago by Phillip Trelford
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.
1 people like thisPosted: 13 years ago by Russell Politzky
An experiment on type-level computations.
4 people like thisPosted: 13 years ago by Nick Palladinos
The snippet implements Async.StartCancellable method that can be used to start a given workflow and then cancel it. The cancellation of the workflow is done asynchronously, which means that the caller will wait until the workflow is actually cancelled.
6 people like thisPosted: 13 years ago by Tomas Petricek
A bit of syntax eye candy for your string building code.
10 people like thisPosted: 13 years ago by Eirik Tsarpalis
Conway's Game of Life example at F#unctional Londoners July 2012 meetup.
2 people like thisPosted: 13 years ago by Phillip Trelford
Rename JSON property names by reconstructing JSON object.
10 people like thisPosted: 13 years ago by Dmitry Lobanov
Calculating the Earth Similarity Index of a planet. http://phl.upr.edu/projects/earth-similarity-index-esi
0 people like thisPosted: 13 years ago by Kit Eason
Implementation of Project Euler question 28.
0 people like thisPosted: 13 years ago by Bret Colloff
This is a simple IoC implementation that allows registration with optional parametrization.
2 people like thisPosted: 13 years ago by Eirik Tsarpalis
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.
0 people like thisPosted: 13 years ago by Eirik Tsarpalis
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/
1 people like thisPosted: 13 years ago by Kit Eason
failwith/failwithf are a useful operators, but they only raise exceptions of type SystemException. Here's a simple way to generalize them.
2 people like thisPosted: 13 years ago by Eirik Tsarpalis
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..]
5 people like thisPosted: 13 years ago by Nicolas2
just some snippets ive been using to play around with async + DNS, nothing production, updated: ipsOfDomain and domainOfIp now both return string array
2 people like thisPosted: 13 years ago by david klein
A minimal interpreter for David Madore's crazy-esoteric programming language.
5 people like thisPosted: 13 years ago by Nick Palladinos
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 **
4 people like thisPosted: 13 years ago by nicolas2
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.
4 people like thisPosted: 13 years ago by Tomas Petricek
A simple script to list the exceptions that can be thrown during the method invocation (both caught and uncaught).
5 people like thisPosted: 13 years ago by Natallie Baikevich
simple affineCipher translated from https://github.com/asweigart/codebreaker/blob/master/affineCipher.py not sure if actually correct. I updated the below to make it easier to understand because I was bored, made some more changes, now pass in lambda as function to pxn instead of individual functions, as suggested by rwbarton for my haskell version.
4 people like thisPosted: 13 years ago by david klein
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.
3 people like thisPosted: 13 years ago by Paulmichael Blasucci
Naive "school-book" implimentation.
14 people like thisPosted: 13 years ago by Kaspar
Here's how to use the [
Posted: 13 years ago by Kit Eason
A pair of extension methods for SerializationInfo that make custom ISerializable implementations much more straightforward to write.
6 people like thisPosted: 13 years ago by Eirik Tsarpalis
The snippet implements 'List.partitionWhile' which behaves as a combination of 'Seq.takeWhile' and 'Seq.skipWhile': It splits the list into a part containing elements from the beginning of a list that match a given predicate and remaining elements.
7 people like thisPosted: 13 years ago by Tomas Petricek
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
3 people like thisPosted: 13 years ago by Tomas Petricek
A batched Deque
2 people like thisPosted: 13 years ago by Nicolas2
A monadic trampoline for stack-overflow free programming.
6 people like thisPosted: 13 years ago by Nick Palladinos
A simple utility that allows making assertions using potentially complex pattern matches.
3 people like thisPosted: 13 years ago by Eirik Tsarpalis
This sample illustrates how to use an IDisposable inside an object, as well as a simple use of object expression
4 people like thisPosted: 13 years ago by nicolas2
A simple extension method for asynchronous non-deterministic computations.
4 people like thisPosted: 13 years ago by 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. UPDATE (11/2015): Following the discussion in https://fslang.uservoice.com/forums/245727-f-language/suggestions/10575069-add-async-choice-to-fsharp-core I have updated the snippet.
3 people like thisPosted: 13 years ago by Eirik Tsarpalis
Code by me and Nick Palladinos.
2 people like thisPosted: 13 years ago by Eirik Tsarpalis
This snippet adds the 'GetSlice' operation to Math.Net vector and matrix types. This makes it possible to get sub-vectors and sub-matrices using the convenient syntax (For vectors 'vect.[start .. end]` or 'vect.[start ..]' and for matrices 'mat.[r1 .. r2, c1 .. c2]' and similar).
9 people like thisPosted: 13 years ago by Tomas Petricek
Square root for integral types
5 people like thisPosted: 13 years ago by ildjarn
An implementation of a CRC-32 algorithm, as described in RFC-1952 "GZIP file format specification version 4.3"
3 people like thisPosted: 13 years ago by Henrik Ravn
Sample for Coding Kata
3 people like thisPosted: 13 years ago by Tomas Petricek
work with ini file with WritePrivateProfileString, GetPrivateProfileString easy as pie
1 people like thisPosted: 13 years ago by nCdy
Generates the value string for the "Authorization:" header given Twitter application/user keys and tokens and the parameters for the request being authorized.
0 people like thisPosted: 13 years ago by Faisal Waris
Generates the value string for the "Authorization:" header given Twitter application/user keys and tokens and the parameters for the request being authorized. Slightly updated to allow additional oauth parameters to be included in the header. This version handles the case when the token is not yet available, i.e. when you want to request a new token/token_secret pair.
2 people like thisPosted: 13 years ago by Faisal Waris
Creates all possible mobile phone letter combinations from a number.
2 people like thisPosted: 13 years ago by Phillip Trelford
Readonly generic Hashtable class implementation example.
4 people like thisPosted: 13 years ago by Phillip Trelford
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.
1 people like thisPosted: 13 years ago by Kit Eason
fold by applying a list of function to a list of arg, last one behaving as usual
1 people like thisPosted: 13 years ago by nicolas2
Applying functions on the n first elements
1 people like thisPosted: 13 years ago by Nicolas2
A Simple Implementation of Lazy Type.
3 people like thisPosted: 13 years ago by Joel Huang
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.
3 people like thisPosted: 13 years ago by Joel Huang
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.
7 people like thisPosted: 13 years ago by Richard Broida
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.
0 people like thisPosted: 13 years ago by Richard Broida
A continuation function takes the result when it is computed. Here is an implementation of sorting on List via insertion.
4 people like thisPosted: 13 years ago by Joel Huang
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.
5 people like thisPosted: 13 years ago by Joel Huang
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!)
0 people like thisPosted: 13 years ago by Kit Eason
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).
1 people like thisPosted: 13 years ago by Richard Broida
Simplification of 'Apply operators to Options' http://fssnip.net/ee using higher order functions. Should also be part of the Option module.
2 people like thisPosted: 13 years ago by @rojepp
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.
4 people like thisPosted: 13 years ago by Cesar Mendoza
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:
3 people like thisPosted: 13 years ago by ZackZhou
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.
1 people like thisPosted: 13 years ago by ZackZhou
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.
1 people like thisPosted: 13 years ago by ZackZhou
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.
8 people like thisPosted: 13 years ago by ZackZhou
the function returns entire files sequence for given root directory, including sub-directories.
1 people like thisPosted: 13 years ago by Michael Gringauz
An implementation of the inverse of Expr.Cast<_>, with erasure happening at reflection level.
3 people like thisPosted: 13 years ago by Eirik Tsarpalis
Adds "enumerable extraction" support to query expressions
7 people like thisPosted: 13 years ago by kvb
This snippet defines a computation builder that sums the squares of float values. It includes Combine, Zero, Yield, Delay, and For operations.
3 people like thisPosted: 13 years ago by Joel Huang
Immutable stack can be implemented via Discriminated Union Type with methods like Push and Pop. The following snippet is a simple version of it.
2 people like thisPosted: 13 years ago by Joel Huang
This function splits a sequence into lists of length n until there is less than n elements then those are returned.
12 people like thisPosted: 13 years ago by Taha Hachana
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.
2 people like thisPosted: 13 years ago by Joel Huang
Simple combinator library to declarative validation.
17 people like thisPosted: 13 years ago by Kaspar
A random pex4fun puzzle to write a snippet to merge two strings.
2 people like thisPosted: 13 years ago by Joel Huang
An Implementation of the Porter Stemming Algorithm in F# for text analysis. Please see: http://tartarus.org/martin/PorterStemmer/
4 people like thisPosted: 13 years ago by Faisal Waris
A quick exploration of the rather useless question "how does the density of the product of 2 sparse matrices look like?"
0 people like thisPosted: 13 years ago by Mathias Brandewinder
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.
6 people like thisPosted: 13 years ago by Jeallyn Duan
Quick & dirty solution to Reversi kata: http://codingdojo.org/cgi-bin/wiki.pl?KataReversi
1 people like thisPosted: 13 years ago by Phillip Trelford
FsSql is originally here: https://github.com/mausch/FsSql and better sample is there too but I just want to share it.
2 people like thisPosted: 13 years ago by Ash Harley
The Official Solution.
0 people like thisPosted: 13 years ago by Nick
Playing with Undertone, using operators for terse tune definitions.
1 people like thisPosted: 13 years ago by Michael Newton
References and type definition to open StackOverflow API over OData
6 people like thisPosted: 13 years ago by Phillip Trelford
Generates the Prime Number Sequence.
2 people like thisPosted: 13 years ago by AdamSpeight2008
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).
1 people like thisPosted: 13 years ago by Joel Huang
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).
1 people like thisPosted: 13 years ago by Kevin Roche
Yet another immutable queue implementation
7 people like thisPosted: 13 years ago by Eirik Tsarpalis
Create a list of int in range [init, upper).
3 people like thisPosted: 13 years ago by Gab_km
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").
4 people like thisPosted: 13 years ago by Kit Eason
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
8 people like thisPosted: 13 years ago by isaiah perumalla
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.
0 people like thisPosted: 13 years ago by Kit Eason
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.
3 people like thisPosted: 13 years ago by Joel Huang
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.
6 people like thisPosted: 13 years ago by Phillip Trelford
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.
4 people like thisPosted: 13 years ago by Joel Huang
Factorial versus tail recursion
4 people like thisPosted: 13 years ago by Laco
fibonacci by Seq.Unfold
2 people like thisPosted: 13 years ago by Laco
An example that shows how we can represent unique names (using classes) and how to substitute names in any F# type type defined using records, discriminated unions and tuples.
0 people like thisPosted: 13 years ago by Tomas Petricek
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.
0 people like thisPosted: 13 years ago by test
A script exported from Try F#
0 people like thisPosted: 13 years ago by chriscanary
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.
4 people like thisPosted: 13 years ago by Kit Eason
A snippet generated by Try F#
0 people like thisPosted: 13 years ago by chrismarinos
A snippet exported from Try F#.
0 people like thisPosted: 13 years ago by chrismarinos
A snippet exported from Try F#.
0 people like thisPosted: 13 years ago by chrismarinos
A snippet exported from Try F#.
11 people like thisPosted: 13 years ago by chrismarinos
A snippet exported from Try F#.
1 people like thisPosted: 13 years ago by chrismarinos
A snippet exported from Try F#.
0 people like thisPosted: 13 years ago by chrismarinos
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.)
2 people like thisPosted: 13 years ago by Kit Eason
Take a sequence and exclude values from it based on another 'suppression list' sequence.
1 people like thisPosted: 13 years ago by Kit Eason
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.
4 people like thisPosted: 13 years ago by Kit Eason
A snippet exported from Try F#.
0 people like thisPosted: 13 years ago by cpoulain
A snippet exported from Try F#.
0 people like thisPosted: 13 years ago by cpoulain
A snippet exported from Try F#.
0 people like thisPosted: 13 years ago by nicolas2
A snippet exported from Try F#.
0 people like thisPosted: 13 years ago by nicolas2
A snippet exported from Try F#.
0 people like thisPosted: 13 years ago by Levert
A snippet exported from Try F#.
0 people like thisPosted: 13 years ago by Levert
given an array n generates all lists with k choices from n
8 people like thisPosted: 13 years ago by isaiah perumalla
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.
5 people like thisPosted: 13 years ago by Eirik Tsarpalis
A snippet exported from Try F#.
0 people like thisPosted: 13 years ago by Levert
only a test
0 people like thisPosted: 13 years ago by chriscanary
only a test
0 people like thisPosted: 13 years ago by chriscanary
another test
0 people like thisPosted: 13 years ago by chriscanary
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.
4 people like thisPosted: 13 years ago by David Klein
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.
7 people like thisPosted: 13 years ago by Eirik Tsarpalis
Variations on some of the LINQ extension members which do not require a type annotation on the lambda argument when used from F#
12 people like thisPosted: 13 years ago by Don Syme
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
4 people like thisPosted: 13 years ago by greg zakharov
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#.
2 people like thisPosted: 13 years ago by David Klein
Example of Lift Curve
0 people like thisPosted: 13 years ago by zman
Example of Lift Curve
0 people like thisPosted: 13 years ago by zman
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
6 people like thisPosted: 13 years ago by user3539
Generate the powerset of a set using a bit pattern.
2 people like thisPosted: 13 years ago by Muigai
test
0 people like thisPosted: 13 years ago by Levert
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.
2 people like thisPosted: 13 years ago by David Klein
Hex string to byte array via sequences
3 people like thisPosted: 13 years ago by Gennady Loskutov
A small snippet that groups sequences of arbitrary unions by branch type.
0 people like thisPosted: 13 years ago by Eirik Tsarpalis
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..)
3 people like thisPosted: 13 years ago by Nicolas2
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.
7 people like thisPosted: 13 years ago by Eirik Tsarpalis
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
2 people like thisPosted: 13 years ago by Muigai
Church numerals via rank-2 polymorphism
4 people like thisPosted: 13 years ago by Nick Palladinos
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).
12 people like thisPosted: 13 years ago by Tomas Petricek
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.
1 people like thisPosted: 13 years ago by Muigai
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
2 people like thisPosted: 13 years ago by Clever people
Type Safe Higher-order abstract syntax via GADT encoding
4 people like thisPosted: 13 years ago by Nick Palladinos
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.
3 people like thisPosted: 13 years ago by Eirik Tsarpalis
This is the minimum F# code required to run and view a compute shader with SlimDX in DirectX 11.
3 people like thisPosted: 13 years ago by gradbot
A compute shader using wang's hash to make a static filled window. Runs at 2000 frames per second on my machine.
1 people like thisPosted: 13 years ago by gradbot
Minimal code to render some colored triangles.
0 people like thisPosted: 13 years ago by gradbot
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
0 people like thisPosted: 13 years ago by Eirik Tsarpalis
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
1 people like thisPosted: 13 years ago by jbuedel
Easy database access.
9 people like thisPosted: 13 years ago by igeta
If I'd entered the same SuperBowl Pool every year, and received the same numbers every year, how much would I have won?
0 people like thisPosted: 13 years ago by Wayne Bradney
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
2 people like thisPosted: 13 years ago by Dmitry Soshnikov
Defines the operator /% as DivRem for int, int64 and bigint.
6 people like thisPosted: 13 years ago by Diego Frata
hackthissite.org programming level 12, string manipulation.
6 people like thisPosted: 13 years ago by David Klein
This fake module can trace pipeline operators.
6 people like thisPosted: 13 years ago by Nobuhisa
Generate password-like string and save it to clipboard. Original idea is here: http://d.hatena.ne.jp/rubyco/20130202/password (Japanese)
3 people like thisPosted: 13 years ago by yukitos
Implemetation picked up from http://msdn.microsoft.com/en-us/library/system.runtime.serialization.objectmanager.aspx
3 people like thisPosted: 13 years ago by Eirik Tsarpalis
Copies a directory of files. Based on code from http://msdn.microsoft.com/en-us/library/bb762914.aspx
3 people like thisPosted: 13 years ago by Wallace Kelly
Accepts a directory and wildcard pattern to delete files in a folder
1 people like thisPosted: 13 years ago by Wallace Kelly
Or who needs non-strict semantics when you have references?
3 people like thisPosted: 13 years ago by Eirik Tsarpalis
Builds a Visual Studio solution.
3 people like thisPosted: 13 years ago by Wallace Kelly
Fast and GC friendly fixpoint combinator.
9 people like thisPosted: 13 years ago by Nick Palladinos
A proof of concept on how one could build an argument parsing scheme simply by declaring a discriminated union.
11 people like thisPosted: 13 years ago by Eirik Tsarpalis
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.
5 people like thisPosted: 13 years ago by Tim Robinson
Reversi Kata solution from February 2013 London F# Meetup Coding Kata.
5 people like thisPosted: 13 years ago by Phillip Trelford
Comparing university enrollment rate in Czech Republic and OECD countries (works in tryfsharp.org!)
2 people like thisPosted: 13 years ago by tomasp
F# to CSS compiler (CSS EDSL in F#) <+> inspired by Clay and FAKE - https://github.com/Cynede/Failess
7 people like thisPosted: 13 years ago by Heather
Evaluates a useful subset of F# quotations at run-time (without the F# PowerPack API).
15 people like thisPosted: 13 years ago by Phillip Trelford
Estimate the value of PI using a Monte Carlo simulation.
5 people like thisPosted: 13 years ago by Phillip Trelford
Agent that can upgrade its functionality on the fly. (F# MailboxProcessor containing function in the loop...)
5 people like thisPosted: 13 years ago by Tuomas Hietanen
This is the code I used to generate this pie chart: http://pic.twitter.com/PgPEFByg56 Enough said?
9 people like thisPosted: 13 years ago by Kit Eason
F# Simulation lab Part III Systems Biology Cambridge University
0 people like thisPosted: 13 years ago by Samin
F# Simulation lab Part III Systems Biology Cambridge University
0 people like thisPosted: 13 years ago by Samin
An abstract class that implements all the boilerplate required for custom comparison semantics.
1 people like thisPosted: 13 years ago by Eirik Tsarpalis
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)
3 people like thisPosted: 13 years ago by Gustavo Guerra
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.
5 people like thisPosted: 13 years ago by Aggelos Biboudis
Project Euler Problem 14
3 people like thisPosted: 13 years ago by Jon Canning
A few active pattern combinators useful when pattern matching on lists is necessary.
2 people like thisPosted: 13 years ago by Eirik Tsarpalis
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#.
4 people like thisPosted: 13 years ago by Greg Ros
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.
2 people like thisPosted: 13 years ago by Greg Ros
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.
18 people like thisPosted: 13 years ago by Tomas Petricek
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.
5 people like thisPosted: 13 years ago by David Klein
An implementation of the ? operator that handles null
3 people like thisPosted: 13 years ago by Tomas Petricek
A crazy experiment for "Scalable" collections. Inspired by the paper "Fighting Bit Rot with Types"
5 people like thisPosted: 13 years ago by Nick Palladinos
http://codekata.pragprog.com/2007/01/kata_five_bloom.html
3 people like thisPosted: 13 years ago by Suzanna
This snippet likes the "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.
9 people like thisPosted: 13 years ago by Nobuhisa
Solution to Kata Six: Anagrams from http://codekata.pragprog.com/2007/01/kata_six_anagra.html in F#
1 people like thisPosted: 13 years ago by Suzanna
Quick function to take a wireshark 'C Structure' and turn it into a F# byte array
3 people like thisPosted: 13 years ago by David Klein
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.
2 people like thisPosted: 13 years ago by Matthew H. Traylor
A simple asynchronous workflow that retries running a given async workflow (until "resultOk" function returns true or until a specified number of retries is performed). The function uses tail-recursion in async workflows.
24 people like thisPosted: 13 years ago by Tomas Petricek
I came up with a gimmick. It looks like function overloading.
8 people like thisPosted: 13 years ago by Nobuhisa
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).
3 people like thisPosted: 13 years ago by Vasily Kirichenko
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.
18 people like thisPosted: 13 years ago by Tomas Petricek
This snippet is an example of how to implement parser combinators in a simple way.
4 people like thisPosted: 13 years ago by Santi Albo
Asynchronously await task completion with timeout support.
9 people like thisPosted: 13 years ago by Eirik Tsarpalis
Asynchronously perform a computation until it completes or timeout is reached.
4 people like thisPosted: 13 years ago by Eirik Tsarpalis
Example on the use of Workflows in parser combinators.
3 people like thisPosted: 13 years ago by Santi Albo
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.
2 people like thisPosted: 13 years ago by Suzanna
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]]
3 people like thisPosted: 13 years ago by Bjørn Bæverfjord
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
5 people like thisPosted: 13 years ago by Faisal Waris
Higher order function
1 people like thisPosted: 13 years ago by Rafael
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).
4 people like thisPosted: 12 years ago by Vasily Kirichenko
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!
1 people like thisPosted: 12 years ago by Richard Griffiths - SoulFireMage
Shows how to generate a Gantt chart to visualize a schedule. Note: Requires BinPacking.fs found here: http://fssnip.net/hG
3 people like thisPosted: 12 years ago by Faisal Waris
The snippet shows how to create an F# function value that will call a custom finalizer function when garbage collected. This is done by creating a type that inherits from FSharpFunc.
8 people like thisPosted: 12 years ago by Tomas Petricek
A basic recursive implementation of merge sort on lists of ints.
1 people like thisPosted: 12 years ago by Bret Colloff
An attempt at defining Peano arithmetic for all numeric types
7 people like thisPosted: 12 years ago by Eirik Tsarpalis
My take at Project Euler #4
1 people like thisPosted: 12 years ago by ildjarn
A combinator that enables real imperative code in F#. Use with caution!
5 people like thisPosted: 12 years ago by Eirik Tsarpalis
So I disposed :(
2 people like thisPosted: 12 years ago by Heather
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 ;)
3 people like thisPosted: 12 years ago by David Klein
http://msdn.microsoft.com/en-us/library/vstudio/dd483467(v=vs.100).aspx
2 people like thisPosted: 12 years ago by Prue
C++ style metaprogramming in F#
5 people like thisPosted: 12 years ago by Nick Palladinos
Parsing simple formulas using active patterns
2 people like thisPosted: 12 years ago by Tomas Petricek
Iterate simple b-tree
3 people like thisPosted: 12 years ago by devshorts
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
3 people like thisPosted: 12 years ago by devshorts
Cleaning up source code for a Forth like language before the compiling stage
1 people like thisPosted: 12 years ago by Bjørn Bæverfjord
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
2 people like thisPosted: 12 years ago by Phillip Trelford
A simple module for registering option types with ServiceStack serializer.
1 people like thisPosted: 12 years ago by Diego Frata
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
2 people like thisPosted: 12 years ago by devshorts
Tests if a string is a palindrome (whitespace independent)
1 people like thisPosted: 12 years ago by devshorts
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.
4 people like thisPosted: 12 years ago by @kot_2010
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.
3 people like thisPosted: 12 years ago by haf
Trying to understand why some type inference used to work in OCaml and not anymore in F#
1 people like thisPosted: 12 years ago by Lasher`
A simple yet powerful library for parallel collection processing. Inspired by Clojure's Reducers.
10 people like thisPosted: 12 years ago by Nick Palladinos
Several ways of counting leading zeros in a binary number. Update: clzDeBruijn now captures the look-up table in the closure so that the table is only evaluated once and everything is contained in the main function.
3 people like thisPosted: 12 years ago by Bjørn Bæverfjord
backup files , construct directory structure and then copy them one by one, ignore some sub directory in ignore list
5 people like thisPosted: 12 years ago by rigid wang
Peeks from a few seq randomly according to specified frequencies. not tested
2 people like thisPosted: 12 years ago by nicolas2
A simple Twitter search function, leveraging the JSON type provider.
9 people like thisPosted: 12 years ago by Lincoln Atkinson
Simple symmetric key cryptogrphy. Ok for low security usages.
5 people like thisPosted: 12 years ago by Faisal Waris
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/
2 people like thisPosted: 12 years ago by Nicolas Dirand
A simple retry combinator with customizable retry policies.
1 people like thisPosted: 12 years ago by Eirik Tsarpalis
Generates a WAVE sound file
10 people like thisPosted: 12 years ago by Phillip Trelford
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.
4 people like thisPosted: 12 years ago by Darren Smith
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.
5 people like thisPosted: 12 years ago by David Klein
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.
5 people like thisPosted: 12 years ago by Ben Clare
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#.
3 people like thisPosted: 12 years ago by Tim Robinson
This uses fparsec to parse locale files of hte form Id = text {arg:type} = newline = newlne For use with localization.
1 people like thisPosted: 12 years ago by devshorts
String split function that skips quoted strings, useful as a simple CSV parser
7 people like thisPosted: 12 years ago by Phillip Trelford
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.
2 people like thisPosted: 12 years ago by David Klein
Everyone else has a concat, so why not Option.
2 people like thisPosted: 12 years ago by Simon Cousins
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.
1 people like thisPosted: 12 years ago by Kit Eason
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
1 people like thisPosted: 12 years ago by Lincoln Atkinson
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
1 people like thisPosted: 12 years ago by Lincoln Atkinson
A cool F# quine
4 people like thisPosted: 12 years ago by Rijnard van Tonder
A bit more functional version of this: http://fssnip.net/iR
2 people like thisPosted: 12 years ago by @kot_2010
This is a small example of invoking Win32 API. It gets the url which is opened by Google chrome's main window.
3 people like thisPosted: 12 years ago by nagat01
File parsing, based on multiple lines, using recursive pattern matching with many :: (cons) operator
2 people like thisPosted: 12 years ago by Tuomas Hietanen
Generic higher-order function to measure timing of a given function
3 people like thisPosted: 12 years ago by Lincoln Atkinson
The simplest F# semicoroutines via seq. comprehensions http://en.wikipedia.org/wiki/Coroutine Replaced a custom function with the pipeline operator.
1 people like thisPosted: 12 years ago by Lakret
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.
1 people like thisPosted: 12 years ago by nagat01
An implementation of session types in F#. Inspired from the paper "Haskell Session Types with (Almost) No Class"
6 people like thisPosted: 12 years ago by Nick Palladinos
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#.
2 people like thisPosted: 12 years ago by Tim Robinson
Delimited continuations encoded as a parameterized continuation monad.
1 people like thisPosted: 12 years ago by Nick Palladinos
F# introduction course - Exploring World Bank data in Try F#
0 people like thisPosted: 12 years ago by Tomas Petricek
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#.
3 people like thisPosted: 12 years ago by Tomas Petricek
F# introduction course - Getting data about Titanic passengers using CSV type provider and analyzing them using standard sequence-processing functions known from LINQ. To be used in Try F#.
1 people like thisPosted: 12 years ago by Tomas Petricek
A F# crash course taught to Year 6 students (11 year olds).
2 people like thisPosted: 12 years ago by Samin Ishtiaq
Parser for Tom's Obvious, Minimal Language (https://github.com/mojombo/toml).
5 people like thisPosted: 12 years ago by nagat01
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#.
7 people like thisPosted: 12 years ago by Tomas Petricek
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 :)
0 people like thisPosted: 12 years ago by nagat01
Bron–Kerbosch algorithm is an algorithm for finding maximal cliques in an undirected graph http://en.wikipedia.org/wiki/Bron%E2%80%93Kerbosch_algorithm
1 people like thisPosted: 12 years ago by Lakret
Calculate the root-mean-square of a dataset. Eg. given the voltages over time of an alternating current, calculate the RMS voltage.
3 people like thisPosted: 12 years ago by Kit Eason
Had to throw together a Haskell-style Either type in F# since Choice is a pain in the ass.
5 people like thisPosted: 12 years ago by Bryan Edds
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.
3 people like thisPosted: 12 years ago by nagat01
A simple library that reads XML documents into user-defined F# types. The user defines a set of discriminated unions that model the elements of the file and a library automatically creates these types from a XML file.
10 people like thisPosted: 12 years ago by Tomas Petricek
Algebraic effects and handlers is a new modular approach for handling effectful computations in functional languages. Inspired from the paper "Handlers in action"
6 people like thisPosted: 12 years ago by Nick Palladinos
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.
1 people like thisPosted: 12 years ago by Tomas Petricek
A function to display digit from ML coding Dojo by Mathais
0 people like thisPosted: 12 years ago by Tomas Petricek
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)
1 people like thisPosted: 12 years ago by Samuel Bosch
Compute the great circle distance of 2 points
3 people like thisPosted: 12 years ago by Samuel Bosch
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, ...)
2 people like thisPosted: 12 years ago by Bram Jochems
Assign value to variable in functional programing language F #.
0 people like thisPosted: 12 years ago by dhruvil007
Display message in f sharp.
0 people like thisPosted: 12 years ago by dhruvil007
Generate a random expression and evaluate it
1 people like thisPosted: 12 years ago by devshorts
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.)
2 people like thisPosted: 12 years ago by Kit Eason
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|]
0 people like thisPosted: 12 years ago by devshorts
Sequence expression which deals with cartesian product of sequences with for ... do expression. It replaces nested for .. do expression to single one.
0 people like thisPosted: 12 years ago by nagat01
A minimalist XML Parser
11 people like thisPosted: 12 years ago by Fabio Galuppo
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
4 people like thisPosted: 12 years ago by Samuel Bosch
If you have a directory containing multiple zip files, unzip them all in one pass. (Requires .NET 4.5)
4 people like thisPosted: 12 years ago by Kit Eason
Binary Search Tree and Depth-First Traversal (PreOrder, InOrder, PostOrder)
6 people like thisPosted: 12 years ago by Fabio Galuppo
Count the number of bits in a bigint (System.Numerics.BigInteger) and a BitArray. Note that version 4 is the fastest.
1 people like thisPosted: 12 years ago by Samuel Bosch
A simple example that shows how to refactor discriminated unions to extract common members
3 people like thisPosted: 12 years ago by Tomas Petricek
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.
3 people like thisPosted: 12 years ago by Eirik Tsarpalis
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).
1 people like thisPosted: 12 years ago by Samuel Bosch
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.
6 people like thisPosted: 12 years ago by Eirik Tsarpalis
See http://stackoverflow.com/questions/18595597/is-using-a-stringbuilder-a-right-thing-to-do-in-f
1 people like thisPosted: 12 years ago by Ramon Snir
A simple trick for defining positive infinity semantics.
3 people like thisPosted: 12 years ago by Eirik Tsarpalis
What feature would I like to see in F#? One thing is the ability to implement an interface in a class by delegating the implementation to an expression. This snippet demonstrates the idea using a simple example of vectors.
7 people like thisPosted: 12 years ago by Tomas Petricek
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.
8 people like thisPosted: 12 years ago by Phillip Trelford
Blow up words to ASCII art with this 5x5 font
7 people like thisPosted: 12 years ago by Phillip Trelford
Converts an excel column identifier like "AR" to a zero-index number
4 people like thisPosted: 12 years ago by David Grenier
test
1 people like thisPosted: 12 years ago by mndrake
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.
0 people like thisPosted: 12 years ago by Sean Newham
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.
5 people like thisPosted: 12 years ago by Eirik Tsarpalis
Splits array into chunks, returning seq of seqs. Works with F# 3.x
3 people like thisPosted: 12 years ago by Lakret
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)
4 people like thisPosted: 12 years ago by Faisal Waris
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
2 people like thisPosted: 12 years ago by Evanescent Devil
Decorator Pattern
2 people like thisPosted: 12 years ago by Evanescent Devil
Factory Pattern
1 people like thisPosted: 12 years ago by Evanescent Devil
Observer Pattern
2 people like thisPosted: 12 years ago by Evanescent Devil
Playing with the OO Strategy Pattern and the F# type system
3 people like thisPosted: 12 years ago by David Grenier
The snippet shows how to define the "=>" operator in F# so that it can be used for creating named parameters for dynamic API.
7 people like thisPosted: 12 years ago by Tomas Petricek
Purges files in bin and obj folders, useful to reduce size when copying project folders. Be careful, this script will delete files!
1 people like thisPosted: 12 years ago by Phillip Trelford
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]
1 people like thisPosted: 12 years ago by devshorts
Lori's module
0 people like thisPosted: 12 years ago by llq
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.
3 people like thisPosted: 12 years ago by musicologyman
Test
0 people like thisPosted: 12 years ago by egerland
Lori's calling module
0 people like thisPosted: 12 years ago by llq
Testing
1 people like thisPosted: 12 years ago by llq
Uses dynamic operator to quickly create XML
3 people like thisPosted: 12 years ago by David Grenier
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).
3 people like thisPosted: 12 years ago by mavnn
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.
3 people like thisPosted: 12 years ago by David Grenier
xBehave QuickStart sample direct conversion to F# from C#: https://github.com/xbehave/xbehave.net/wiki/Quickstart
1 people like thisPosted: 12 years ago by Phillip Trelford
xBehave QuickStart sample conversion to F# from C# with some helper functions: https://github.com/xbehave/xbehave.net/wiki/Quickstart
1 people like thisPosted: 12 years ago by Phillip Trelford
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
1 people like thisPosted: 12 years ago by Phillip Trelford
Here's a very short, very simple, example for Algebraic Manipulation of the equation x + y = z
0 people like thisPosted: 12 years ago by Virgil
Another version of the xBahve quick start example, this time using custom F# computation builder to make the code nicer. We define a builder for step and custom functions for Given/And/When/Then.
3 people like thisPosted: 12 years ago by Tomas Petricek
An F# wrapper for HtmlAgilityPack
9 people like thisPosted: 12 years ago by Gustavo Guerra
Filter by list of properties when provider supports filter expressions but doesn't support Contains. Equivalent C# : https://gist.github.com/mausch/6893533
2 people like thisPosted: 12 years ago by Mauricio Scheffer
With love to Ilker...
2 people like thisPosted: 12 years ago by sforkmann
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.
3 people like thisPosted: 12 years ago by Alpha Diallo
Log file parser for log4Net files
3 people like thisPosted: 12 years ago by Tuomas Hietanen
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.
5 people like thisPosted: 12 years ago by Samuel Bosch
User Story 1 from the Bank OCR Kata: http://codingdojo.org/cgi-bin/wiki.pl?KataBankOCR
1 people like thisPosted: 12 years ago by Phillip Trelford
See: http://codingdojo.org/cgi-bin/wiki.pl?KataBankOCR Prog. F# 2013 - London
2 people like thisPosted: 12 years ago by Zach Bray
SkillsMatter 2013 F# Tutorials Programming with the Stars Code Snippet
1 people like thisPosted: 12 years ago by Rickasaurus
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.
0 people like thisPosted: 12 years ago by nagat01
From progfsharp tutorials
0 people like thisPosted: 12 years ago by mavnn
Simple, but slow. Don't do this at home :)
0 people like thisPosted: 12 years ago by mavnn
Actors with control actor. No mutable state.
3 people like thisPosted: 12 years ago by Tuomas Hietanen
Huffman coding in F#. frenchCode courtesy of M.Odersky.
2 people like thisPosted: 12 years ago by nicolas
bank OCR code parse from London's ProgF# 2013
1 people like thisPosted: 12 years ago by Daniel Kovi
When printing None via printfn (or any of the other print functions for that matter), the result is
Posted: 12 years ago by Dave Fancher
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.
1 people like thisPosted: 12 years ago by Onorio Catenacci
Selection of helper functions for generating test data.
1 people like thisPosted: 12 years ago by mavnn
Lazily generate fizzbuzz results and provide a test function. Parameterize the inputs and predicates.
1 people like thisPosted: 12 years ago by Ryan Riley
An implementation of a minimum spanning tree calculation algorithm based on Kruskal's algorithm
2 people like thisPosted: 12 years ago by Faisal Waris
Convert a BitArray to a sequence.
1 people like thisPosted: 12 years ago by Samuel Bosch
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%.
2 people like thisPosted: 12 years ago by tonyabell
Demonstration of the manyproc sample from Erlang using F# MailboxProcessor.
3 people like thisPosted: 12 years ago by Ryan Riley
High performance asynchronous Logging module with time-based rollover and size-based file retention in under a 100 lines of F# Bug fix: Fixed log file name date time from "yyyyMMddhhmm" to yyyyMMddHHmm" (24 hour clock)
6 people like thisPosted: 12 years ago by Faisal Waris
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).
0 people like thisPosted: 12 years ago by visProcessEngg
Sample retail domain model, using F# types (records and discriminated unions) with JSON sample data using F# Data type provider.
5 people like thisPosted: 12 years ago by Tomas Petricek & Phil Trelford
Simple implementation of interval and fuzzy calculus.
0 people like thisPosted: 12 years ago by Dmitry Sevastianov
A simple implementation of the Douglas-Peucker path reduction algorithm. Use for simplifying curves, for instance in plotting coastlines. Loosely based on this implementation: http://karthaus.nl/rdp/
5 people like thisPosted: 12 years ago by Kit Eason
Tomas has released their F# data analysis library called Deedle, I just got around to playing with it. It looks really cool!
4 people like thisPosted: 12 years ago by Joel Huang
Factorial recursive function using match with pattern.
0 people like thisPosted: 12 years ago by gg00xiv
Factorial recursive function using match ... with pattern.
0 people like thisPosted: 12 years ago by gg00xiv
For example executable, install NPM and stylus package.
0 people like thisPosted: 12 years ago by Sergey Kaspar
Identify differences between two generally aligned strings.
4 people like thisPosted: 12 years ago by Kit Eason
Useful if you are writing to the console from multiple threads and want to avoid goofed up text
4 people like thisPosted: 12 years ago by Darren Smith
Small Basic abstract syntax tree, interpreter and embedded DSL. Supports Small Basic's keywords and arithmetic, logical and comparison operators.
11 people like thisPosted: 12 years ago by Phillip Trelford
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.
11 people like thisPosted: 12 years ago by Jon Harrop
Print a byte buffer in the same way unix tool hexdump would.
3 people like thisPosted: 12 years ago by Robert Pickering
A more f#ish version of Robert's version http://fssnip.net/l9
1 people like thisPosted: 12 years ago by thinkbeforecoding
A different, sketchy attempt at hexdump.
3 people like thisPosted: 12 years ago by Kit Eason
Querying a players table grouped by first, then by the last name and counting the number of occurrence
14 people like thisPosted: 12 years ago by -H-M-
Get/put field/property and invoke method (one and multi arguments) via "?" operator.
3 people like thisPosted: 12 years ago by Zhukoff Dima
.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.
1 people like thisPosted: 12 years ago by Eirik Tsarpalis
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).)
6 people like thisPosted: 12 years ago by Jack Fox
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.
0 people like thisPosted: 12 years ago by Antonio Parata
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
0 people like thisPosted: 12 years ago by Faisal Waris
Learn Key Principle of F# in just a few minutes with the following Sample of "World Bank Type Provider - Exploring Population Data"
383 people like thisPosted: 12 years ago by Muhammad Mugees Asif
String.notNullOrEmpty extension to strings
2 people like thisPosted: 12 years ago by Tuomas Hietanen
Using task based async, won't block the thread.
2 people like thisPosted: 12 years ago by Tuomas Hietanen
This is a pattern I knocked together to address the issue of global mutable state in the F# compiler.
3 people like thisPosted: 12 years ago by Eirik Tsarpalis
Solution to the layout binary tree problem from 99 OCaml problems
3 people like thisPosted: 12 years ago by Darren Platt, Tomas Petricek
Write graph as dgml file
6 people like thisPosted: 12 years ago by loony
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.
5 people like thisPosted: 12 years ago by Tomas Petricek
Discussion here http://stackoverflow.com/a/21434034/801189
3 people like thisPosted: 12 years ago by V.B.
Match the first elements of an array an returns tail.
3 people like thisPosted: 12 years ago by thinkbeforecoding
brute force pattern building for an array tail
0 people like thisPosted: 12 years ago by timvw
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
4 people like thisPosted: 12 years ago by Zhukoff Dima
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.
4 people like thisPosted: 12 years ago by Phil Brooks
This is the getting started sample for the numl machine learning library available at http://numl.net/ written in F#.
4 people like thisPosted: 12 years ago by Taha Hachana
Simple and a more optimized implementation of the azimuthal equidistant projection. Input is expected in degrees.
3 people like thisPosted: 12 years ago by Samuel Bosch
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.
3 people like thisPosted: 12 years ago by Robert Nielsen
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.
1 people like thisPosted: 12 years ago by Robert Nielsen
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
2 people like thisPosted: 12 years ago by Samuel Bosch
Example active pattern for tweet.
1 people like thisPosted: 12 years ago by Robert Nielsen
calcula la matriz inversa
0 people like thisPosted: 12 years ago by ivpadim
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
1 people like thisPosted: 12 years ago by @BrockSamsonUK
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.
1 people like thisPosted: 12 years ago by Robert Nielsen
A function to initialize 2D array that supports failures - if the initializer fails to produce value for any of the array locations, the construction is stopped and the function returns 'None'
3 people like thisPosted: 12 years ago by Tomas Petricek
Compute MD5 hash of a string
2 people like thisPosted: 12 years ago by Kit Eason
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.
4 people like thisPosted: 12 years ago by Alan Wostenberg
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.
1 people like thisPosted: 12 years ago by Anonymous
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.
2 people like thisPosted: 12 years ago by Michael Parker
One solution to Rosalind rabbits problem.
2 people like thisPosted: 12 years ago by Michel Caradec
Type provider for acceess more datafile via class property.
5 people like thisPosted: 12 years ago by Zhukoff Dima
This is a Pigeon/Akka actor based on pure (if you remove printf) function instead of inheriting from a class..
1 people like thisPosted: 12 years ago by thinkbeforecoding
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
Posted: 12 years ago by mavnn
This time with recursive function through computation expression around continuations...
2 people like thisPosted: 12 years ago by thinkbeforecoding
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.
2 people like thisPosted: 12 years ago by John Tarbox
A simple function that creates a counter function (with localized mutable state).
2 people like thisPosted: 12 years ago by Tomas Petricek
Tired of confusing dictionary instances with different comparers (I am)? Stick it in the type, à la ocaml-core maps.
4 people like thisPosted: 12 years ago by Mauricio Scheffer
This snippet shows how to transform simple recursive factorial function to combinator form step-by-step.
2 people like thisPosted: 12 years ago by Dmitri Soshnikov
"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/
4 people like thisPosted: 12 years ago by FunctionalSoftware.net
A simple example that creates a frame from a list of dictionaries. Each dictionary is treated as a row that maps column keys to values. The trick is to use Deedle value expansion.
1 people like thisPosted: 12 years ago by Tomas Petricek
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).
8 people like thisPosted: 12 years ago by Faisal Waris
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.
6 people like thisPosted: 12 years ago by nagat01
A different way of expressing private DU constructors.
8 people like thisPosted: 12 years ago by iceypoi
Helper modules for different kinds of memoize functions.
1 people like thisPosted: 12 years ago by Daniel Fabian (@iceypoi)
For tutorial, the same functionality, different styles of pattern matching.
4 people like thisPosted: 11 years ago by Tuomas Hietanen
For tutorial, example how to use option type.
3 people like thisPosted: 11 years ago by Tuomas Hietanen
Small quiz-game with World Bank TypeProvider (from FSharp.Data Nuget-package): Which country has the capital city of (random capital)? (Three options)
3 people like thisPosted: 11 years ago by Tuomas Hietanen
Knocked together a bare-minimum TCP wrapper for MailboxProcessor. Not intended for production.
7 people like thisPosted: 11 years ago by Eirik Tsarpalis
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.
4 people like thisPosted: 11 years ago by Eirik Tsarpalis
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
4 people like thisPosted: 11 years ago by Eirik Tsarpalis
Shuffling array using Seq.fold
6 people like thisPosted: 11 years ago by Karlkim Suwanmongkol
Prints a list in a spiral
3 people like thisPosted: 11 years ago by devshorts
Check string of palindroms
2 people like thisPosted: 11 years ago by Zhukoff Dima
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://nut-cracker.azurewebsites.net/typeclasses-for-fsharp) with numeric literals. But FsControl is removed to completely avoid unnecessary function calls.
4 people like thisPosted: 11 years ago by Daniel Fabian (@iceypoi)
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.
7 people like thisPosted: 11 years ago by Tore Green
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.
2 people like thisPosted: 11 years ago by Jonathan Leaver
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.
13 people like thisPosted: 11 years ago by Fabio Galuppo
Convenience function to easily throw an argument exception with a helpful string description. Looks simple, but was hard to figure out.
1 people like thisPosted: 11 years ago by Wallace Kelly
Just something I whipped up to check out the Marvel Comics API using JSON Type Provider
1 people like thisPosted: 11 years ago by David Grenier
A few short usage examples for the FSharp.Date Type Provider (available on Nuget).
3 people like thisPosted: 11 years ago by Phillip Trelford
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
1 people like thisPosted: 11 years ago by Tony Lee
A script suitable for FSI that copies a (UTF-8) text file throwing away uninteresting lines in the process.
2 people like thisPosted: 11 years ago by Robert Nielsen
Different ways to write lazy values - using the lazy keyword or the Lazy.Create function. Pick the one you like the most!
2 people like thisPosted: 11 years ago by Tomas Petricek
Just a quick and dirty hack
2 people like thisPosted: 11 years ago by Eirik Tsarpalis
Smallest divisible number between 1 to any number.
0 people like thisPosted: 11 years ago by FoXyCon
Using Type Provider generated functions for type safe logging.
0 people like thisPosted: 11 years ago by mavnn
Memoize from _real world functional programming_ by Petricek and Skeet chapter 10 tutorial
5 people like thisPosted: 11 years ago by Alan Wostenberg
This is a translation to F# of the Haskell code in the article "FizzBuzz in Haskell by Embedding a Domain-Specific Language" by Maciej Piróg The original article is located here: http://themonadreader.files.wordpress.com/2014/04/issue23.pdf The idea is to help people familiar with F# but not with Haskell to follow the article.
1 people like thisPosted: 11 years ago by Cesar Mendoza
One of Jenkin's hash functions
6 people like thisPosted: 11 years ago by RViscarra
Function that converts a base 10 number into a base 26 (digits from the English alphabet) one. A=1, B=2, ..., Z=0
1 people like thisPosted: 11 years ago by Lars Wilhelmsen
How to generate functions for copying F# record-array-union trees with Expr.
1 people like thisPosted: 11 years ago by Rick Minerich
Plays the perfect game of Tic-Tac-Toe using the Negamax algorithm.
2 people like thisPosted: 11 years ago by Richard Dalton
A simple script that checks whether 1.0 is really the identity element of multiplication for 32bit floating-point numbers.
0 people like thisPosted: 11 years ago by Tomas Petricek
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.
2 people like thisPosted: 11 years ago by Bjørn Bæverfjord
Zip file type provider
2 people like thisPosted: 11 years ago by Zhukoff Dima
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.
1 people like thisPosted: 11 years ago by Samuel Bosch
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.
3 people like thisPosted: 11 years ago by Chris Ballard
single-case DU with shadowed constructor for passing non-primitives around that are already validated.
5 people like thisPosted: 11 years ago by ImaginaryDevelopment.blogspot.com
Full source code for my blog entry on this subject - http://chrsb.co/BNqAbM
1 people like thisPosted: 11 years ago by Chris Ballard
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.
1 people like thisPosted: 11 years ago by Samuel Bosch
@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 :)
2 people like thisPosted: 11 years ago by Chris Ballard
An extra primitive that can be used to safely unbox to Some
Posted: 11 years ago by 7sharp9
following http://vimeo.com/groups/97577/videos/97315970 to make my own html DSL
1 people like thisPosted: 11 years ago by Brandon Dimperio (@MaslowJax)
Forgotten file for F# Works |> Paris!!!
4 people like thisPosted: 11 years ago by Tomas Petricek
A fun little trick.
3 people like thisPosted: 11 years ago by BR
Different ways of generating numerical ranges in F#. It turns out that the built-in syntax generates fairly slow code, so the snippet shows two alternative ways that are faster. Any compiler optimizations making the built-in one faster would be nice :-)
6 people like thisPosted: 11 years ago by Tomas Petricek
Simple Cost Study
0 people like thisPosted: 11 years ago by NicolasDobler
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'
1 people like thisPosted: 11 years ago by Tomas Petricek
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.
0 people like thisPosted: 11 years ago by Martin Bodocky
Small F# snippet on how to read 32-bit integers from a file at specific indexes.
5 people like thisPosted: 11 years ago by Samuel Bosch
263 bytes (unix line endings ;))
6 people like thisPosted: 11 years ago by Simon Dickson
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.
1 people like thisPosted: 11 years ago by @BrockSamsonUK
Somewhat implementation coupled, but the ideas are pretty neat. works in linqpad, not sure what's up with this editor
2 people like thisPosted: 11 years ago by Brandon Dimperio (@MaslowJax)
Test Anything Protocol runner for NUnit lets you run unit tests within an F# interactive session.
3 people like thisPosted: 11 years ago by Phillip Trelford
This sample uses the internals of the Freebase type provider to get the names of all the entities that Freebase knows about. The snippet returns the type names, so some of the type provider internals are exposed, but it still returns nice list of entities.
0 people like thisPosted: 11 years ago by Tomas Petricek
This script finds all possible divisors of a number
1 people like thisPosted: 11 years ago by Knerd
Make the (!) operator even more useful by duck typing it. Simple and effective!
5 people like thisPosted: 11 years ago by Sami Perttu
Extension for Async module: channel for transmitting data between subsystems, launching parallel groups of asyncs sequentially.
5 people like thisPosted: 11 years ago by dvitel
A quick NodaTime.Instant generator for FsCheck
3 people like thisPosted: 11 years ago by mavnn
Backtracking search for Constraint Satisfaction Problems (CSP)
4 people like thisPosted: 11 years ago by Fabio Galuppo
Minimal Logo implementation using FParsec with support for procedures.
9 people like thisPosted: 11 years ago by Phillip Trelford
Demonstration Hall Paradox Game1 xxx - 1 strategy; Game2 xxx - 2 strategy (change choice).
1 people like thisPosted: 11 years ago by Zhukoff Dima
Async demo...
3 people like thisPosted: 11 years ago by Tomas Petricek
Agent demo
12 people like thisPosted: 11 years ago by Tomas Petricek
Using Azure Table Storage with WindowsAzure.Storage
3 people like thisPosted: 11 years ago by Tuomas Hietanen
It's probably not possible, but I'm going to see how far I can get...
1 people like thisPosted: 11 years ago by mavnn
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/
3 people like thisPosted: 11 years ago by Joe C
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.
12 people like thisPosted: 11 years ago by Tomas Petricek
Suggestion for a core library function.
2 people like thisPosted: 11 years ago by Eirik Tsarpalis
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
2 people like thisPosted: 11 years ago by Ruben Bartelink
Single Case Active Patterns
1 people like thisPosted: 11 years ago by tamizhvendan
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).
2 people like thisPosted: 11 years ago by Kevin Roche
Type extensions for ASCII strings represented as byte arrays. Note: requires the F# 3.1 compiler.
3 people like thisPosted: 11 years ago by Phillip Trelford
Find what's been added, removed or changed between two lists (perfom a diff between two lists of items).
4 people like thisPosted: 11 years ago by Daniel Bradley
test of Async.StartWithContinuations
1 people like thisPosted: 11 years ago by omanuke
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.
5 people like thisPosted: 11 years ago by Daniel Bradley
Reversing RELEASE_NOTES.md Very ugly version hacked together in a minute
0 people like thisPosted: 11 years ago by Gustavo Guerra
Simple example of Eto library usage for drawing
5 people like thisPosted: 11 years ago by Antonio Cisternino
A simple example of a decorator pattern using object expressions and the pipeline operator for a fluent interface
2 people like thisPosted: 11 years ago by Steve Goguen
An example of the composite pattern implemented simply with functions and object expressions
2 people like thisPosted: 11 years ago by Steve Goguen
A work-in-progress implementation of Lambda Calculus - Alpha and Beta reduction is buggy
1 people like thisPosted: 11 years ago by Steve Goguen
Lock-free, mutable list that supports multi-threading scenarios.
4 people like thisPosted: 11 years ago by Ruxo Zheng
Solves the "Two Logicians" puzzle.
3 people like thisPosted: 11 years ago by Vandroiy
This is a simple way to flat a two dimensional array in a linear one
1 people like thisPosted: 11 years ago by Riccardo Terrell
Naive performance comparison of push model libraries: Reactive Extension (Rx), Observable module (built-in to F#) and Nessos Streams. Note: smaller numbers are better
12 people like thisPosted: 11 years ago by Phillip Trelford
Implements a simple agent that lets you throttle the degree of parallelism by limiting the number of work items that are processed in parallel.
7 people like thisPosted: 11 years ago by Tomas Petricek
Script to render a Koch snowflake using a Windows Forms bitmap.
4 people like thisPosted: 11 years ago by Phillip Trelford
Transparent snowflake using polygons and rotational symmetry, based on paper and scissors method.
3 people like thisPosted: 11 years ago by Phillip Trelford
A more idiomatic definition of a Rational type with custom operators.
1 people like thisPosted: 11 years ago by Tomas Petricek
Casts list of objects to any other type. Return objects if cast is possible, so new list can be shorter (or empty).
4 people like thisPosted: 11 years ago by RLinde
Playing with simplified domain modules and event sourcing in F#
6 people like thisPosted: 11 years ago by mavnn
построение дерева решений
0 people like thisPosted: 11 years ago by fpawel
построение дерева решений
2 people like thisPosted: 11 years ago by fpawel
graham scan algorithm for finding the convex hull of a set of 2-dimensional points
0 people like thisPosted: 11 years ago by albertpang
Works by forcing yourself to close Outlook and then notifies you an hour later.
4 people like thisPosted: 11 years ago by David Grenier
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.
8 people like thisPosted: 11 years ago by Phillip Trelford
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.
7 people like thisPosted: 11 years ago by Phillip Trelford
Removes the nth element from a list
2 people like thisPosted: 11 years ago by Antonio Prestes García
Generates a sequence of dates (ascending or descending), incrementing (or decrementing) by one day at a time, inclusive of the start and end dates.
3 people like thisPosted: 11 years ago by Daniel Bradley
Analyse word count from files. You can use it e.g. to create Tag Clouds
3 people like thisPosted: 11 years ago by Tuomas Hietanen
Microsoft Kinect Body Basics with Kinect SDK 2.0 and F-Sharp
7 people like thisPosted: 11 years ago by Tuomas Hietanen
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
2 people like thisPosted: 11 years ago by Phillip Trelford
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
2 people like thisPosted: 11 years ago by Tuomas Hietanen
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.
3 people like thisPosted: 11 years ago by Antonio Prestes García
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.
3 people like thisPosted: 11 years ago by Vasily Kirichenko
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.
2 people like thisPosted: 11 years ago by Vasily Kirichenko
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
7 people like thisPosted: 11 years ago by Anthony Perez
https://github.com/tpetricek/FSharp.Joinads/blob/master/src/Joins/Samples.fs#L60 ported to Hopac.
1 people like thisPosted: 11 years ago by Vasily Kirichenko
This is "Parallel tree processing" example from http://tryjoinads.org/ ported straitforwardly to Hopac.
3 people like thisPosted: 11 years ago by Vasily Kirichenko
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.
1 people like thisPosted: 11 years ago by Taha Hachana
Adding together Option types
5 people like thisPosted: 11 years ago by mavnn
Idea from Guy L. Steele - Organizing Functional Code for Parallel Execution; or, foldl and foldr Considered Slightly Harmful - https://vimeo.com/6624203
9 people like thisPosted: 11 years ago by Tuomas Hietanen
Querying NuGet package manager via OData TypeProvider
3 people like thisPosted: 11 years ago by Tuomas Hietanen
This simple snippet shuffles the elements of a list. It can be useful for simulations.
4 people like thisPosted: 11 years ago by Antonio Prestes García
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
4 people like thisPosted: 11 years ago by Riccardo Terrell
A function that will take a sequence of directory names and recursively find and return a sequence of all file names within.
11 people like thisPosted: 11 years ago by Andreas Ågren
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!)
8 people like thisPosted: 11 years ago by Kit Eason
Continuing from https://twitter.com/JKPappas/status/558339587719045120, here's an approach on extending units of measure to arbitrary types.
18 people like thisPosted: 11 years ago by Eirik Tsarpalis
A type-level SAT solver in F#, inspired by https://gist.github.com/wouter-swierstra/0b6062c9660e751cd535
5 people like thisPosted: 11 years ago by Nick Palladinos
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.
7 people like thisPosted: 11 years ago by Riccardo Terrell
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.
4 people like thisPosted: 11 years ago by Krunoslav Saho
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.
16 people like thisPosted: 11 years ago by Neil Danson
Extended from: http://www.fssnip.net/d2
1 people like thisPosted: 11 years ago by Rick Minerich
Trying to set a string option
2 people like thisPosted: 11 years ago by joobus
Taken from FSharpx.
2 people like thisPosted: 11 years ago by ane
Async extensions for Socket. This extensions use SocketAsyncEventArgs, not Begin / End pattern.
2 people like thisPosted: 11 years ago by sayuri
How to print a formatted calendar to the console using F#
12 people like thisPosted: 11 years ago by Fabio Galuppo
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
2 people like thisPosted: 11 years ago by mavnn
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.
2 people like thisPosted: 11 years ago by Anton Tcholakov
Generate timebased one time passwords, for use with tools like google authenticator, etc.
3 people like thisPosted: 11 years ago by @sillyotter
See also https://fslang.uservoice.com/forums/245727-f-language/suggestions/6536829-implement-ocaml-s-new-match-exception-syntax
3 people like thisPosted: 11 years ago by Eirik Tsarpalis
Attempt to reproduce caseInsensitiveString from http://stackoverflow.com/a/12938883/17049
2 people like thisPosted: 11 years ago by Gauthier Segay
Extract images from all resources's ressources of all assmeblies in a folder
2 people like thisPosted: 11 years ago by Gauthier Segay
Simple retail domain for Tesco with scan, cancel and tendering and calculation of total price.
3 people like thisPosted: 11 years ago by Tomas Petricek & Phil Trelford
Getting started with Akka.NET
7 people like thisPosted: 11 years ago by Tuomas Hietanen
Turn a project based nuspec into a project type paket template (see http://fsprojects.github.io/Paket/template-files.html )
3 people like thisPosted: 11 years ago by mavnn
Counting 1-bits in a DWORD (int32) using the 'divide and conquer' strategy
2 people like thisPosted: 11 years ago by Fabio Galuppo
Overrides the standard Web API ApiControllerActionInvoker with one that works with controller actions return F# Async<'T> results.
5 people like thisPosted: 11 years ago by Ryan Riley
Formatting a Timespan to something fully descriptive and user friendly.
4 people like thisPosted: 11 years ago by Gauthier Segay
Normalisation of "F# quotations" by evaluation.
4 people like thisPosted: 11 years ago by Nick Palladinos
This is just the ML code from http://jozefg.bitbucket.org/posts/2015-02-28-type-inference.html ported to F#.
3 people like thisPosted: 11 years ago by Rick Minerich
This is a "library" for validation that collects all validation errors (and does not use the heavy-weight machinery of monads). This is perhaps a simpler variant that could be used e.g. here: http://tinyurl.com/lv2nwkl
7 people like thisPosted: 11 years ago by Tomas Petricek
test
1 people like thisPosted: 11 years ago by chet
Playing with Chiron for JSON storage.
5 people like thisPosted: 11 years ago by mavnn
Prototype of a CIL code optimizer that generates optimal code for bitwise functions. Update: General improvements
2 people like thisPosted: 11 years ago by Bjørn Bæverfjord
Game evolution
0 people like thisPosted: 11 years ago by Paul Orland
Game evolution
2 people like thisPosted: 11 years ago by Paul Orland
Parsing cron expression and calculating next launch time from schedule. v 1.1: bugs fixed for case */n + catch bad parsings
4 people like thisPosted: 11 years ago by dvitel
"let rec inline" doesn't always behave as expected
2 people like thisPosted: 11 years ago by mavnn
FizzBuzz using Active Patterns.
7 people like thisPosted: 11 years ago by Nathan Smith
sequence fibbonaci
2 people like thisPosted: 11 years ago by vasya pupkin
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
3 people like thisPosted: 11 years ago by orlandow
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!
2 people like thisPosted: 11 years ago by warnerBro19
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.
4 people like thisPosted: 10 years ago by Jonathan Leaver
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
2 people like thisPosted: 10 years ago by Phillip Trelford
When you get an exception from the F# Compiler Service, it usually does not print any useful information. But you can look at the private fields of the exception and get some more useful things out of it...
0 people like thisPosted: 10 years ago by Tomas Petricek
A very simple function to print hello world, which is completely useless. Just testin the F# Snippets API...
1 people like thisPosted: 10 years ago by Tomas Petricek
3D castle sample from the Fun3D project, now written using WebGL and running in a web browser...
2 people like thisPosted: 10 years ago by Tomas Petricek
Utility module to more naturally use mutable Dictionary type from Collections library
5 people like thisPosted: 10 years ago by Ville Vainio
a
1 people like thisPosted: 10 years ago by a
castle
2 people like thisPosted: 10 years ago by castle
No nulls FsCheck
2 people like thisPosted: 10 years ago by mavnn
Palindrome test.
2 people like thisPosted: 10 years ago by Pitch Rock
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.
3 people like thisPosted: 10 years ago by Eirik Tsarpalis
c.f. http://fssnip.net/qR In this example different syntactic structures result in different types.
0 people like thisPosted: 10 years ago by Eirik Tsarpalis
Flatten Nested Type
0 people like thisPosted: 10 years ago by Pitch Rock
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.
2 people like thisPosted: 10 years ago by Vesa Karvonen
Replace elements
2 people like thisPosted: 10 years ago by Pitch Rock
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.
2 people like thisPosted: 10 years ago by Evelina Gabasova
Compress List
2 people like thisPosted: 10 years ago by Pitch Rock
Rotate List
2 people like thisPosted: 10 years ago by Pitch Rock
Sample code snippet to group the data into buckets
3 people like thisPosted: 10 years ago by Tamizhvendan
Simplistic helpers for formatting dates and strings in a web server (strip HTML tags when reading RSS feeds, nicely format dates etc.)
2 people like thisPosted: 10 years ago by Tomas Petricek
Trigroup
2 people like thisPosted: 10 years ago by Pitch Rock
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
3 people like thisPosted: 10 years ago by Faisal Waris
Functional programming operators related to the BCL ImmutableDictionary type.
5 people like thisPosted: 10 years ago by Phillip Trelford
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.
3 people like thisPosted: 10 years ago by Eirik Tsarpalis
Parses UNIX time stamp into DateTime (as returned for example by the OpenWeatherMap API)
5 people like thisPosted: 10 years ago by Tomas Petricek
https://twitter.com/kot_2010/status/607115335255392256
0 people like thisPosted: 10 years ago by Tamizhvendan
Solution to Viral Math Problem From Vietnam explained on: http://mindyourdecisions.com/blog/2015/05/20/viral-math-problem-from-vietnam-are-you-smarter-than-an-8-year-old/#.VXhmhs-eDRY
1 people like thisPosted: 10 years ago by HK
just a test of fun3d
1 people like thisPosted: 10 years ago by Hodza Nassredin
changed x and z dimensions
2 people like thisPosted: 10 years ago by Hodza Nassredin
Example of integrating DotLiquid with a simple Suave server. The snippet automatically registers all public members of a record as members that can be accessed by DotLiquid templates.
5 people like thisPosted: 10 years ago by Tomas Petricek
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!)
2 people like thisPosted: 10 years ago by Kit Eason
Write a function last : 'a list -> 'a option that returns the last element of a list.
0 people like thisPosted: 10 years ago by DC F#
Find the last but one (last and penultimate) elements of a list. (easy)
0 people like thisPosted: 10 years ago by DC F#
Find the k'th element of a list. (easy)
0 people like thisPosted: 10 years ago by DC F#
f# has Seq.length but we ask that you reimplement it. Bonus for a tail recursive solution.
0 people like thisPosted: 10 years ago by DC F#
One of the 99 OCaml problems rewritten in F#
0 people like thisPosted: 10 years ago by Vladimir Khorikov
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.
3 people like thisPosted: 10 years ago by Anton Tcholakov
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.
2 people like thisPosted: 10 years ago by Anton Tcholakov
One of the problems from https://ocaml.org/learn/tutorials/99problems.html
0 people like thisPosted: 10 years ago by Vladimir Khorikov
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
3 people like thisPosted: 10 years ago by manofstick
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.
2 people like thisPosted: 10 years ago by Anton Tcholakov
One script to create MS-SQL-database and host OWIN Web-server with SignalR-clients
1 people like thisPosted: 10 years ago by Tuomas Hietanen
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
2 people like thisPosted: 10 years ago by Fabio Galuppo
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.
6 people like thisPosted: 10 years ago by Antonio Cisternino
Flappy bird clone script using WPF, click the mouse or hit space to flap, no collision detection.
6 people like thisPosted: 10 years ago by Phillip Trelford
Flappy bird clone script using MonoGame, click the mouse or hit space to flap, no collision detection.
3 people like thisPosted: 10 years ago by Phillip Trelford
A snippet with a working (minimal) example of a Kerbal Space Program (www.kerbalspaceprogram.com) add-on in F#. The snippet is intended to help you get started with Unity add-on development in F#.
1 people like thisPosted: 10 years ago by Robert Nielsen
Created during the morning session of Progressive.Net 2015 with Phil Trelford
1 people like thisPosted: 10 years ago by Chris O'Dell
Created during the morning session of Progressive.Net 2015 with Phil Trelford
1 people like thisPosted: 10 years ago by John Donnellan
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
1 people like thisPosted: 10 years ago by Dom Finn
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.
5 people like thisPosted: 10 years ago by Tomas Petricek
Factorial with bigint and reduce
2 people like thisPosted: 10 years ago by Andriy Tolstoy
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
3 people like thisPosted: 10 years ago by Phillip Trelford
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.
4 people like thisPosted: 10 years ago by John Nolan, Callum Simpson
This function compiles an F# quotation to a JavaScript string, or prints errors to stderr and returns None on failure.
4 people like thisPosted: 10 years ago by Loïc `Tarmil` Denuzière
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.
1 people like thisPosted: 10 years ago by Bryan Edds
Fibonacci nth term with fold
6 people like thisPosted: 10 years ago by Andriy Tolstoy
Inspired by @theburningmonk, this snippet defines a couple of extensions and operators that can be used to make F# as short and as obscure as APL. Complete with a 19 character solution of the Euler problem #1!
7 people like thisPosted: 10 years ago by Tomas Petricek
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.
1 people like thisPosted: 10 years ago by Anton Tcholakov
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.
3 people like thisPosted: 10 years ago by Anton Tcholakov
A snippet demonstrating the F# feature request to relax some of the indentation rules.
2 people like thisPosted: 10 years ago by Tomas Petricek
Example of how to use F# to create websites in IIS
2 people like thisPosted: 10 years ago by Dom Finn
Safe get for the Option type
0 people like thisPosted: 10 years ago by let rec
Alternative solution to the problem in Scott Wlaschin's "Reinventing the Reader Monad" article (but without monads).
3 people like thisPosted: 10 years ago by Tomas Petricek
Helper Type Extension to convert a System.Threading.Tasks.Task to IObservable.
1 people like thisPosted: 10 years ago by Riccardo Terrell
Helper Type Extension to convert an Async computation to IObservable.
4 people like thisPosted: 10 years ago by Riccardo Terrell
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
3 people like thisPosted: 10 years ago by Tomas Petricek
This is a somewhat sensible solution to the flappy bird dojo by Phil Trelford. It uses sequence expressions eliminate some mutation of the flappy bird. To play this sample on Windows simply copy the code from the raw view and execute in F# interactive, for cross platform implementations check out: http://trelford.com/prognet15.zip
6 people like thisPosted: 10 years ago by Tomas Petricek
Barebone Reactive Extensions web server demo.
7 people like thisPosted: 10 years ago by Giacomo Stelluti Scala
Function to read a wav file
1 people like thisPosted: 10 years ago by albertp007
Function to perform the Graham scan algorithm which looks for the set of points forming the convex hull of the input points
4 people like thisPosted: 10 years ago by albertp007
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.
3 people like thisPosted: 10 years ago by Tomas Petricek
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.
2 people like thisPosted: 10 years ago by Vesa Karvonen
Select right russian word for number of days
0 people like thisPosted: 10 years ago by runiner
Drops 1000 randomly generated pictures in C:\temp. Based on Andrej Bauer's Random Art implementation: http://www.random-art.org/about/
3 people like thisPosted: 10 years ago by Phillip Trelford
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
3 people like thisPosted: 10 years ago by Kristian Schmidt
An alternative Async.RunSynchronously implementation that avoids the performance bug as recorded in https://github.com/Microsoft/visualfsharp/issues/581
2 people like thisPosted: 10 years ago by Eirik Tsarpalis
Using F# 4.0 Automatic Quotations to mutate provided XML documents with static type checking
2 people like thisPosted: 10 years ago by Green Eagle Solutions
Bitmap primitives helper functions for manipulating bitmap in memory as an array of tuples (x,y,color).
2 people like thisPosted: 10 years ago by Giacomo Stelluti Scala
Using FSharpOption
Posted: 10 years ago by Gauthier Segay
String percentual similarity using Levenshtein Distance, as described in https://en.wikipedia.org/wiki/Levenshtein_distance.
0 people like thisPosted: 10 years ago by Giacomo Stelluti Scala
Simple type arithmetic with Peano numbers, using a recursive type and pattern matching over it.
1 people like thisPosted: 10 years ago by Giacomo Stelluti Scala
Wrap TryParse in an option.
5 people like thisPosted: 10 years ago by Craig Boucher
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/
2 people like thisPosted: 10 years ago by Sami Perttu
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!
3 people like thisPosted: 10 years ago by Vesa Karvonen
Simple fs script to convert a wql statement to a json string
3 people like thisPosted: 10 years ago by max
To avoid too huge lists when doing recursion, SQL-IN-clauses, etc... Use the F# core version: chunkBySize
2 people like thisPosted: 10 years ago by Tuomas Hietanen
Fast version - http://www.fssnip.net/sB
2 people like thisPosted: 10 years ago by Zhukoff Dima
Examples of Infinite Streams defined using a lazy fixed-point combinator.
4 people like thisPosted: 10 years ago by Nick Palladinos
Staged Fixed-point combinator.
5 people like thisPosted: 10 years ago by Nick Palladinos
Application of staging to "scrap your boilerplate" generic programming technique.
2 people like thisPosted: 10 years ago by Nick Palladinos
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.
1 people like thisPosted: 10 years ago by mavnn
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
2 people like thisPosted: 10 years ago by mavnn
Snippet for assignment problem of module 3
3 people like thisPosted: 10 years ago by Nic Lef
target type statically type constrained tryParse function over all .Net types implementing static TryParse functions.
4 people like thisPosted: 10 years ago by George Dennie
Staged fixed-point combinator without staged recursion.
3 people like thisPosted: 10 years ago by Nick Palladinos
im in ur forms, updating ur snippets!
0 people like thisPosted: 10 years ago by Tomas Petricek
Jelmer047.fsx
1 people like thisPosted: 10 years ago by jelmer
class on learning F#
1 people like thisPosted: 10 years ago by fairflow
Modern and efficient algorithm to generate prime numbers up to certain number Uses Parallel Async to run computations in parallel
4 people like thisPosted: 10 years ago by Sergey OCHKIN
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.
2 people like thisPosted: 10 years ago by Tomas Petricek
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"
2 people like thisPosted: 10 years ago by Hugh Gleaves
Create a circular (repeating) sequence from an input sequence, optionally limiting the total number of elements.
0 people like thisPosted: 10 years ago by Hugh Gleaves
This snippet computes the infinite sequence of points that form Sierpinski triangle, and draws this fractal figure using FSharp.Charting
5 people like thisPosted: 10 years ago by Dmitry Soshnikov
How to fold a tree left branch first.
1 people like thisPosted: 10 years ago by krgn
Fibonacci sequence with scan
5 people like thisPosted: 10 years ago by Andriy Tolstoy
HttpListener + FParsec + Pattern Matching = Simple REST Endpoints
3 people like thisPosted: 10 years ago by Ted Cackowski Jr
Yet Another Fizz Buzz (YAFB)
8 people like thisPosted: 10 years ago by @Functional_S
Quick script using FsLab that visualizes the aggregate number of downloads of a NuGet package over time, using the HTML type provider to get the data from www.nuget.org.
2 people like thisPosted: 10 years ago by Tomas Petricek
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.
5 people like thisPosted: 10 years ago by Nick Lydon
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
6 people like thisPosted: 10 years ago by thinkbeforecoding
Calculate the Flesch Reading Ease Score for a string or a file. https://en.wikipedia.org/wiki/Flesch%E2%80%93Kincaid_readability_tests
1 people like thisPosted: 10 years ago by Kit Eason
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.
2 people like thisPosted: 10 years ago by Sami Perttu
F# lambda (quotation) to C# Expression
Posted: 10 years ago by Tuomas Hietanen
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.
5 people like thisPosted: 10 years ago by Tomas Petricek
Top Trump petition signatures by constituency & their 2015 election results using F# Data's CSV & JSON providers
4 people like thisPosted: 10 years ago by Phillip Trelford
Write BMP in ARGB uncompressed 32-bits per-pixel format
3 people like thisPosted: 10 years ago by Phillip Trelford
Partial evaluating the Ackermann function.
2 people like thisPosted: 10 years ago by Nick Palladinos
Slicing arrays without copying using .Net's ArraySegment struct
2 people like thisPosted: 10 years ago by Phillip Trelford
Generic Type-level Fold for Boolean Algebra
0 people like thisPosted: 10 years ago by Nick Palladinos
A first attempt at implementing symbolic exception stacktraces in computation expressions using reflection.
5 people like thisPosted: 10 years ago by Eirik Tsarpalis
Print conflicting .NET assembly references (https://gist.github.com/brianlow/1553265 ported to an F# script)
1 people like thisPosted: 10 years ago by Simon Cousins
A staged a regular expression interpreter is a compiler!!!
4 people like thisPosted: 10 years ago by Nick Palladinos
The Sierpinski carpet is a plane fractal first described by Wacław Sierpiński in 1916.
2 people like thisPosted: 10 years ago by Phillip Trelford
A simple way to render the F# logo with integer scaling to avoid aliasing
4 people like thisPosted: 10 years ago by Bjørn Bæverfjord
Soundex is a phonetic algorithm for indexing names by sound, as pronounced in English implemented in F#. https://en.wikipedia.org/wiki/Soundex
5 people like thisPosted: 10 years ago by Fabio Galuppo
Suave.EvReact is a small library for transforming HTPP request to Suave into events that are orchestrated using EvReact expressions.
6 people like thisPosted: 10 years ago by Antonio Cisternino
Example of using SQL Server Management Objects (SMO) to copy a database from one server to another.
2 people like thisPosted: 10 years ago by jeremyh
An example that showcases why AsyncBuilder.Bind() overloads for task inputs is unfit for F#
3 people like thisPosted: 10 years ago by Eirik Tsarpalis
A little website that lets you make CORS requests to it (update to the latest Suave version)
9 people like thisPosted: 10 years ago by vilinski
Extension methods to List<'T> (aliased ResizeArray<'T> in F#) that provide optimised item removal for unordered lists where item order is not significant.
5 people like thisPosted: 10 years ago by Phillip Trelford
A sitemap-based url tester that runs in parallel.
43 people like thisPosted: 15 years ago by Ryan Riley
Multi-currency report (generated as HTML) based on example given at the start of chapter one of Kent Beck's Test-Driven Development by Example book.
4 people like thisPosted: 10 years ago by Phillip Trelford
Read a password from the command line, masking input with an asterisk. Only tested on Windows 10.
7 people like thisPosted: 10 years ago by TMVector
FParsec parser and Windows Forms viewer for minimal Turtle DSL.
3 people like thisPosted: 11 years ago by Phillip Trelford
Instead of writing template instanciation by hand, this generate a Templates.fs file with all templates given a directory tree containing .html files.
2 people like thisPosted: 10 years ago by Gauthier Segay
A function that is like 'Seq.choose' but stops producing values as soon as the first 'None' value is produced.
3 people like thisPosted: 10 years ago by Tomas Petricek
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.
2 people like thisPosted: 10 years ago by David Neale
Allows you to pretty print a quotation.
7 people like thisPosted: 10 years ago by Colin Bull
Imperative and simple version for Collatz Conjecture or 3n + 1 Problem
1 people like thisPosted: 10 years ago by Fabio Galuppo
Functional and simple version for Collatz Conjecture or 3n + 1 Problem
5 people like thisPosted: 10 years ago by Fabio Galuppo
A prototype of an associative fold operation when the function passed in arguments is a Semigroup(*) Operation. (*) Semigroup from Abstract Algebra.
2 people like thisPosted: 10 years ago by Fabio Galuppo
Here's how to send an email through SMTP. Works from FSI provided you are an authenticated user for the SMTP server. (Vandalism reverted.)
5 people like thisPosted: 10 years ago by Kit Eason
Detect Linux, OSX, or Windows with a handy discriminated union
3 people like thisPosted: 10 years ago by Jack Mott
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.
7 people like thisPosted: 10 years ago by Phillip Trelford
Simple OWIN Self-Host web-server with static files support and request deflate/gzip compression.
3 people like thisPosted: 9 years ago by Tuomas Hietanen
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.
5 people like thisPosted: 9 years ago by Tuomas Hietanen
Get local IPv4-address of the computer
1 people like thisPosted: 9 years ago by Tuomas Hietanen
Calculate distance between two GPS latitude-longitude points.
3 people like thisPosted: 9 years ago by Tuomas Hietanen
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.
2 people like thisPosted: 9 years ago by Robert Nielsen
Two encodings of van Laarhoven style lenses allowing polymorphic updates
3 people like thisPosted: 9 years ago by Vesa Karvonen
Work in progress example on lenses and traversals.
4 people like thisPosted: 9 years ago by Vesa Karvonen
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.
5 people like thisPosted: 9 years ago by Tomas Petricek
excelColumnName 0 = "A" excelColumnName 1 = "B" excelColumnName 545 = "UBB" excelColumnName -1 = exception
3 people like thisPosted: 9 years ago by Gauthier Segay
Give a way to apply captures values on a given function
1 people like thisPosted: 9 years ago by cboudereau
Async task computation expression, in order to avoid Async.AwaitTask for C# interop
3 people like thisPosted: 9 years ago by cboudereau
BELLMAN-FORD algorithm to the shortest path based on pseudo code in Algortihms Unlocked
4 people like thisPosted: 9 years ago by Fabio Galuppo
Magic 8 Ball in your console/terminal
2 people like thisPosted: 9 years ago by Fabio Galuppo
Simple Async Workflow computation expression overload to support task operations.
3 people like thisPosted: 9 years ago by Riccardo Terrell
Implementation of ParallelWithThrottle to limit the number of threads created for an asynchronous Seq.map operation
8 people like thisPosted: 9 years ago by Riccardo Terrell
Message Passing sample inspired by Erlang Ping Pong from here: http://erlang.org/doc/getting_started/conc_prog.html
3 people like thisPosted: 9 years ago by Fabio Galuppo
This is a tool to run model in F# and to tune a MIP. We run sequentially a MIP using different parameters
2 people like thisPosted: 9 years ago by Marko Blais
Quite similar to http://www.fssnip.net/eg but authentication, html-messages and async sending.
4 people like thisPosted: 9 years ago by Tuomas Hietanen
Generic Numeric Literals and Compile time Peano arithmetic
1 people like thisPosted: 9 years ago by Nick Palladinos
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.
3 people like thisPosted: 9 years ago by Tuomas Hietanen
A simple example of using datatype generic JSON operations from Infers.Toys.
5 people like thisPosted: 9 years ago by Vesa Karvonen
Counter part for http://www.fssnip.net/1n
4 people like thisPosted: 9 years ago by Tuomas Hietanen
A starter OWIN Web Server with Web API
3 people like thisPosted: 9 years ago by Ryan Kilkenny
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
2 people like thisPosted: 9 years ago by Dmitry Achkasov
Fetch EUR based currency rates of the day.
1 people like thisPosted: 9 years ago by Tuomas Hietanen
Reading the F# snippets RSS feed using the F# Data XML type provider. Look, you now get tool tips for type providers too!
1 people like thisPosted: 9 years ago by Tomas Petricek
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)
0 people like thisPosted: 9 years ago by Christoph Alrich
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).
2 people like thisPosted: 9 years ago by Tomas Petricek
Solve the 8 queens problem in F#, keeping available positions on the board as a list of X,Y coordinates.
2 people like thisPosted: 9 years ago by Tomas Petricek
Extension methods which greatly simplify using Option<'t> from C# code.
5 people like thisPosted: 9 years ago by Paulmichael Blasucci
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).
3 people like thisPosted: 9 years ago by Tomas Petricek
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.
2 people like thisPosted: 9 years ago by Antonio Cisternino
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.
2 people like thisPosted: 9 years ago by Antonio Cisternino
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.
3 people like thisPosted: 9 years ago by Antonio Cisternino
Analyze results of the fsharpWorks annual F# community survey to figure out what are the most popular F# tools and libraries. The snippet does some minimal data cleanup, but more work is needed to get precise results!
1 people like thisPosted: 9 years ago by Tomas Petricek
Scan folder of views and generate websharper template type provider instanciation code in a file
2 people like thisPosted: 9 years ago by Gauthier Segay
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.
0 people like thisPosted: 9 years ago by Tomas Petricek
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.
6 people like thisPosted: 9 years ago by Daniel Bradley
Two different approaches to the problem of starting with a value, applying a function to it n times, and accumulating a result.
0 people like thisPosted: 9 years ago by Kit Eason
F# port of https://github.com/g0d/Pythia/. All the awesomeness of the original + purely functional!
1 people like thisPosted: 9 years ago by g0d
A SIMD enhanced fold function that adds on to the Array type
2 people like thisPosted: 9 years ago by Jack Mott
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).
0 people like thisPosted: 9 years ago by Hugh Gleaves
Generate Include scripts leveraging paket generate-include-scripts
0 people like thisPosted: 9 years ago by Gauthier Segay
Generate Include scripts leveraging paket generate-include-scripts
1 people like thisPosted: 9 years ago by Gauthier Segay
Generate Include scripts leveraging paket generate-include-scripts
0 people like thisPosted: 9 years ago by Gauthier Segay
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
0 people like thisPosted: 9 years ago by Jose Iborra
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.
0 people like thisPosted: 9 years ago by Hugh Gleaves
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.
3 people like thisPosted: 9 years ago by Jack Mott
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.
1 people like thisPosted: 9 years ago by Jack Mott
Correct and Incorrect Way to Use ConcurrentDictionary
8 people like thisPosted: 9 years ago by Tuomas Hietanen
The snippet shows how to extract list of Olympic medalists from the Rio 2016 web site in a nice JSON format. It turns out you just need the right regular expression to extract the data from a script tag...
2 people like thisPosted: 9 years ago by Tomas Petricek
Finds potential page titles in a HTML page.
1 people like thisPosted: 9 years ago by Phillip Trelford
adhoc example
0 people like thisPosted: 9 years ago by Acme
This handy snippet calculates how much memory your Slack client uses. Use at your own risk. Mental safety cannot be guaranteed.
3 people like thisPosted: 9 years ago by Tomas Petricek
Do you want to format F# snippets, but cannot easily run the F# Formatting library as part of your documentation processing? We just added F# Formatting as a service (FAAS!) API to the F# Snippets. This code snippet shows how to call the service.
2 people like thisPosted: 9 years ago by Tomas Petricek
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.
7 people like thisPosted: 9 years ago by Tuomas Hietanen
Fusion via reducer partial application, based on http://manojo.github.io/resources/staged-fold-fusion.pdf
3 people like thisPosted: 9 years ago by Nick Palladinos
Generate rss news feed from a list of F# record items using Linq2Xml. To use e.g. to generate feeds from your web server.
2 people like thisPosted: 9 years ago by Tuomas Hietanen
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
6 people like thisPosted: 9 years ago by Zdenek Pavlis
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
1 people like thisPosted: 9 years ago by Avnish C. Patel
Given a string containing spinning expressions in the form "{string1|string2|...|stringN}", returns a string content randomly spinned. Spinning expressions can be nested. For instance, the spinned results of string "a{b|{c1|c2}}" will be one of the following : "ab" "ac1" "ac2"
5 people like thisPosted: 9 years ago by Didier Colin
Staged CPS Regular Expression Matcher based on CPS RegEx matcher in http://dl.acm.org/citation.cfm?id=968582
4 people like thisPosted: 9 years ago by Nick Palladinos
Quotations to A-Normal form based on http://matt.might.net/articles/a-normalization/
0 people like thisPosted: 9 years ago by Nick Palladinos
Sums a sequence of decimal digits by repeatedly adding pairs of digits resulting in a single digit result.
3 people like thisPosted: 9 years ago by Hugh Gleaves
Staged Parser Combinators
2 people like thisPosted: 9 years ago by Nick Palladinos
Example of a WPF/Silverlight Attached Property (AP). This is a port of a C# AP implementation that can be found at http://www.silverlightshow.net/items/Attached-Properties-in-Silverlight.aspx.
0 people like thisPosted: 9 years ago by Daniel Mohl
Works with F# 4.0 and above
7 people like thisPosted: 9 years ago by Eirik Tsarpalis
a simple CQRS example, inspired by the blogpost http://tojans.me/blog/2014/02/26/cqrs-and-functional-programming/
6 people like thisPosted: 9 years ago by Andreas Vilinski
Staged Functional Unparsing based on http://www.brics.dk/RS/98/12/BRICS-RS-98-12.pdf
0 people like thisPosted: 9 years ago by Nick Palladinos
Faster with much better quality random numbers than System.Random. See https://en.wikipedia.org/wiki/Xorshift
0 people like thisPosted: 9 years ago by Faisal Waris
Provides a better implementation of Async.AwaitTask where the actual exception of a failing task is passed to the async mechanism.
12 people like thisPosted: 9 years ago by Eirik Tsarpalis
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.
3 people like thisPosted: 9 years ago by Tuomas Hietanen
How you can programmatically use GraphViz from F#.
8 people like thisPosted: 9 years ago by Tuomas Hietanen
Works with System.Drawing Color
2 people like thisPosted: 9 years ago by Faisal Waris
Staged Monoidal Folds based on https://github.com/Gabriel439/slides/blob/master/munihac/foldmap.md
1 people like thisPosted: 9 years ago by Nick Palladinos
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.
4 people like thisPosted: 9 years ago by Faisal Waris
Parser for CNTK error log file (see https://www.microsoft.com/en-us/research/product/cognitive-toolkit/) tested with version 2.0 beta. The parser can be combined with other tooling such as F# chart to view live error rates, etc. (includes a unix 'tail' like function)
1 people like thisPosted: 9 years ago by Faisal Waris
Weak Equality type, useful for various GADT encodings.
2 people like thisPosted: 9 years ago by Nick Palladinos
This function takes an input sequence and returns a function that returns the elements in the sequence one by one when called consecutively. The returned function will throw if called more times than there are elements in the sequence. Useful when unit testing.
3 people like thisPosted: 9 years ago by Peder Sørensen
Lightweight Staged Numeric code.
1 people like thisPosted: 9 years ago by Nick Palladinos
Related to https://github.com/Microsoft/visualfsharp/issues/2127
1 people like thisPosted: 9 years ago by Eirik Tsarpalis
TypeShape-driven FsCheck random generator generator with support for arbitrary POCOs
3 people like thisPosted: 9 years ago by Eirik Tsarpalis
Staged generic hashcode generation using TypeShape.
0 people like thisPosted: 9 years ago by Eirik Tsarpalis
Staged generic equality comparer using TypeShape.
1 people like thisPosted: 9 years ago by Eirik Tsarpalis
Generic Parser Generator for F# values using TypeShape and FParsec. Supports recursive types.
4 people like thisPosted: 9 years ago by Eirik Tsarpalis
CNTK is Microsoft's deep learning toolkit. This snippets allows one to view the live error rate on a chart. It relies on FSharp.Charting and FSharp.Control.Reactive and a couple of other F# snippets the links for which are referenced in the code. Use 'track' function to start viewing live charts.
1 people like thisPosted: 9 years ago by Faisal Waris
This is a simple port in F# of the R/S Hurst exponent
1 people like thisPosted: 9 years ago by antiluv
A fast generic Json serializer for F# types using TypeShape and FParsec
4 people like thisPosted: 9 years ago by Eirik Tsarpalis
An attempt to implement murmurhash version 3 in F# Original source code: https://github.com/aappleby/smhasher/blob/master/src/MurmurHash3.cpp Original author: Austin Appleby Wikpedia link: https://en.wikipedia.org/wiki/MurmurHash
4 people like thisPosted: 9 years ago by Mårten Lindblad
A fast and lightweight json web token (JWT) creator and validator.
3 people like thisPosted: 9 years ago by Sebastian Fialka
A generic map using TypeShape
1 people like thisPosted: 9 years ago by Eirik Tsarpalis
A ksprintf implementation that optionally formats the string. Naive microbenchmarks are provided to demonstrate potential performance gains. See also https://github.com/eiriktsarpalis/TypeShape/blob/d782bcd7fd32b1899c1c95ba933da0ae5e0bb4eb/samples/ksprintf.fsx
1 people like thisPosted: 9 years ago by Eirik Tsarpalis
Euler method is a first-order numerical procedure for solving ordinary differential equations (ODEs) with a given initial value.
1 people like thisPosted: 9 years ago by Ivan Padron
Lagrange's interpolation formula
7 people like thisPosted: 9 years ago by Ivan Padron
Using FSharp.Data
2 people like thisPosted: 9 years ago by Tuomas Hietanen
This is just an initial example / tech-demo.
4 people like thisPosted: 9 years ago by Tuomas Hietanen
Imperative and fast implementation of an intersperse function for array. if you search for a functional implemenation you should look [here](http://www.fssnip.net/7S3/title/Intersperse-a-list).
0 people like thisPosted: 9 years ago by Tobias Burger
Tail recursive implementation of an intersperse function.
2 people like thisPosted: 9 years ago by Tobias Burger
A simple evaluator for F# quotations using TypeShape
2 people like thisPosted: 9 years ago by Eirik Tsarpalis
Applicative style argument accumulator functions inspired by the FParsec.Pipes library. It works by weaving a single continuation argument like a chain, kind of like the pipe function of FParsec but with a arbitrary number of arguments.
3 people like thisPosted: 9 years ago by Marko Grdinić
Not working attempt to do a recursive left associative parser
2 people like thisPosted: 9 years ago by Arno den Uijl
TypeShape-driven structural projection and isomorphism generation
0 people like thisPosted: 9 years ago by Eirik Tsarpalis
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.
1 people like thisPosted: 9 years ago by Hugh Gleaves
Recursive definition of the fibonacci sequence
1 people like thisPosted: 9 years ago by Zaid
The extra type variables can be packed to obj/unpacked from obj so that the type of Optic would have just the 's, 'a, 'b and 't type variables, but I leave that and other further developments out from this example.
3 people like thisPosted: 9 years ago by Vesa Karvonen
F# adaptation of a solution to the expression problem using object algebras, c.f. https://www.cs.utexas.edu/~wcook/Drafts/2012/ecoop2012.pdf
2 people like thisPosted: 9 years ago by Eirik Tsarpalis
This example uses the same data and methods as http://accord-framework.net/docs/html/T_Accord_Statistics_Models_Regression_LogisticRegression.htm
8 people like thisPosted: 9 years ago by Tuomas Hietanen
Parsers a minimal expression tree allowing for functions of the form "func(arg1,arg2,...)->{body}"
5 people like thisPosted: 8 years ago by devshorts
Staged Higher-order abstract syntax via GADT encoding.
0 people like thisPosted: 8 years ago by Nick Palladinos
Staged Higher-order abstract syntax via GADT encoding.
4 people like thisPosted: 8 years ago by Nick Palladinos
For clean initialization of Grids, StackLayouts etc., and other Views with simple click handlers
2 people like thisPosted: 8 years ago by Charles Roddie
Improved version of http://fssnip.net/pm/title/Extending-units-of-measure-to-arbitrary-types that adopts the "type class" approach and sheds requirement for passing the witness type when tag/untagging UoM values.
3 people like thisPosted: 8 years ago by Eirik Tsarpalis
Converts the string representation of a number in-place to an Int32. A return value of None indicates the conversion failed.
4 people like thisPosted: 8 years ago by Phillip Trelford
SRTP and active patterns tricks for mimicking Typescript union types
8 people like thisPosted: 8 years ago by Evgeniy Andreev
Example follows this, translated to FSharp: https://msdn.microsoft.com/en-us/library/dn903708.aspx Just instead of copy&pasting C#, add a new F# class library and paste this code to there, then add that to reference to your C#-project.
3 people like thisPosted: 8 years ago by Tuomas Hietanen
There are several maze creation algorithms (http://www.astrolog.org/labyrnth/algrithm.htm). The interesting point about Growing Tree one is that it turns into the others (for example, Recursive Backtracker and Prim's algo) when we choose the next step in different ways. Check it with tryfsharp.org.
4 people like thisPosted: 8 years ago by Natallie Baikevich
Re-hash of the Free-monad interpreter by erdeszt https://gist.github.com/erdeszt/f8b351b5e6ec4fd903ef based on http://programmers.stackexchange.com/a/242803/145941
5 people like thisPosted: 8 years ago by amieres
Transform a Free Monad interpreter to a compiler through staging.
2 people like thisPosted: 8 years ago by Nick Palladinos
From Löb's Theorem to Spreadsheet Evaluation, based on http://blog.sigfpe.com/2006/11/from-l-theorem-to-spreadsheet.html.
0 people like thisPosted: 8 years ago by NIck Palladinos
From Löb's Theorem to Spreadsheet Evaluation (memoized), based on http://blog.sigfpe.com/2006/11/from-l-theorem-to-spreadsheet.html
2 people like thisPosted: 8 years ago by NIck Palladinos
Function to get all possible combinations of list items. There are some Euler problems (like 77 & 78) to get total amounts. But e.g. for some card game implementations you will need the real items.
4 people like thisPosted: 8 years ago by Tuomas Hietanen
Turtle interpreter example using Mono's Gtk# library with example paths for MonoDevelop (running on Linux) and Xamarin Studio (running on Mac and Windows).
2 people like thisPosted: 8 years ago by Phillip Trelford
Function Composition Operator
1 people like thisPosted: 8 years ago by Luiz Monad
Staged Ziria Streams, based on https://github.com/dimitriv/ziria-sem/blob/master/Haskell/ZirBasic.hs.
0 people like thisPosted: 8 years ago by NIck Palladinos
Downloads Open, High, Low, Close, and Volume data for a stock from Google Finance. Needs Deedle.
2 people like thisPosted: 8 years ago by Fernando Saldanha
Calculates profitability of a Bitcoin mining operation today (February 25, 2017) using current difficult level, Bitcoin price and a state of the art Bitcoin miner.
2 people like thisPosted: 8 years ago by Ademar Gonzalez
GitHub has a public JsonApi to expose file download count.
0 people like thisPosted: 8 years ago by Tuomas Hietanen
Computation builder for async access.
1 people like thisPosted: 8 years ago by Zhukoff Dima
Staged typed formatting, based on http://okmij.org/ftp/ML/GADT.txt, https://www.cl.cam.ac.uk/~jdy22/papers/modular-macros.pdf
0 people like thisPosted: 8 years ago by NIck Palladinos
SortableBindingList suitable for use with WinForms DataGridView.
2 people like thisPosted: 8 years ago by Mike Weiss
Staged Parallel Ziria Streams.
1 people like thisPosted: 8 years ago by NIck Palladinos
A simple CSV writer implementation as two type extensions for the Seq module. Use it with Records, Classes and Tuples. Have a look at the modified CSV reader sample from Don Symes Expert F# too http://fssnip.net/3T in order to advance this snippet using the ColumnAttribute
This version adds quote enclosure support and support for seq
Posted: 8 years ago by Rainer Schuster
Fast Fourier Transform algorithm inspired by the snippet http://fssnip.net/dC/title/fast-Fourier-transforms-FFT-. The original snippet was a beautiful and idiomatic implementation based on the definition of FFT. This version sacrifices idioms and elegance for performance. For data sets with 1024 samples this version seems to be about 100x faster and easier on the GC.
3 people like thisPosted: 8 years ago by Mårten Rånge
Authenticate to Azure with Service Principal //https://docs.microsoft.com/en-us/dotnet/azure/dotnet-sdk-azure-authenticate?view=azure-dotnet#mgmt-auth
0 people like thisPosted: 8 years ago by Jack Fox
yin-yang puzzle, based on https://groups.google.com/forum/#!msg/comp.lang.scheme/Fysq_Wplxsw/awxEZ_uxW20J
0 people like thisPosted: 8 years ago by NIck Palladinos
Staged Trampoline.
1 people like thisPosted: 8 years ago by NIck Palladinos
This is the F# translation of the Scala program written for https://functional.works-hub.com/blog/Type-classes-from-OO-perspective. F# doesn't have implicits, so type classes don't work. However, it's interesting to see just how close you can come by passing an instance of the implementation. By flipping the parameters, you can use partial application to create type-specific functions. Here, we follow the use of the interface, but we could also use statically resolved type parameters to structurally infer different implementations.
4 people like thisPosted: 8 years ago by Ryan Riley
Similar to http://fssnip.net/7Tr, this implementation translates the Scala from https://functional.works-hub.com/blog/Type-classes-from-OO-perspective but uses statically resolved type parameters to show how something similar could be done with computation expression instances. It's really too bad you have to pass an instance of the implementation. It would be nice to be able to specify a module or class with a static member.
3 people like thisPosted: 8 years ago by Ryan Riley
Defines a generic `mutate : 'T -> 'T` function that structurally mutates every value in the object graph, without performing new allocations. Needless to say, this is intended for educational purposes only.
3 people like thisPosted: 8 years ago by Eirik Tsarpalis
Counting Evens and Odds via Z3.
1 people like thisPosted: 8 years ago by NIck Palladinos
Wine-quality decision-tree using machine-learning tool Accord.Net with F#
1 people like thisPosted: 8 years ago by Tuomas Hietanen
Countdown problem via Z3.
2 people like thisPosted: 8 years ago by NIck Palladinos
In statistics, one of the standard ways to calculate an estimate/estimation quality, to be able to compare how good are different estimates.
1 people like thisPosted: 8 years ago by Tuomas Hietanen
Recursive Factorial using Int64, Double and BigInteger with execution time.
0 people like thisPosted: 8 years ago by Carlos Quintanilla
Lightweight syntax for creating tasks using computation expressions
8 people like thisPosted: 8 years ago by Eirik Tsarpalis
A lightweight result type definition without requirement for new types or explicit conversions.
6 people like thisPosted: 8 years ago by Eirik Tsarpalis
Staged Generic Programming with support for recursive types PoC
0 people like thisPosted: 8 years ago by Eirik Tsarpalis
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 an alternative to http://www.fssnip.net/oS
5 people like thisPosted: 8 years ago by Fernando Saldanha
Eternity 2 Solver via Z3.
2 people like thisPosted: 8 years ago by NIck Palladinos
Checks if a string is all in upper-case characters
2 people like thisPosted: 8 years ago by Martin Lockstrom
Generic, structural IDisposable generator for algebraic data types.
2 people like thisPosted: 8 years ago by Eirik Tsarpalis
A generic function that randomly permutes the elements of a sequence.
0 people like thisPosted: 8 years ago by Taha Hachana
Discovering Life patterns via Z3.
3 people like thisPosted: 8 years ago by NIck Palladinos
More parallel calculating alternative option for ``mine to correct`` for http://www.fssnip.net/7RY/title/Using-NBitcoin-to-create-private-BlockChain-with-F-FSharp
0 people like thisPosted: 8 years ago by Tuomas Hietanen
Discovering multistep Life patterns via Z3.
2 people like thisPosted: 8 years ago by NIck Palladinos
It seems original design for struct tuples doesn't contain struct versions of fst and snd functions. SRTP FTW!
3 people like thisPosted: 8 years ago by Evgeniy Andreev
https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/1099
2 people like thisPosted: 8 years ago by journeyman
This sample show how to use seq-yield syntax to convert a binary tree to a sequence of elements.
3 people like thisPosted: 8 years ago by Dmitry Soshnikov
We can use active patterns for methods deconstruction. It allow to hide some rough SRTP syntax.
11 people like thisPosted: 8 years ago by Evgeniy Andreev
The Eff monad in F#, based on http://okmij.org/ftp/Computation/free-monad.html.
3 people like thisPosted: 8 years ago by NIck Palladinos
f# short and sweet may help beginners. Score on winning a point, Winning number first and other players is labeled: b example "0",b ->"15", b. A special case of draw-deuce is "40", "A" -> "40","40" If player 2 wins a point score calling is flipped as 2->score(b,a). fold (fun to call for each element in the test list) (initials "0","0") [test list of winning player] Notice f# is perhaps easier and clearer than pseudo code and verbose description. An improvement suggestion for Don is if syntax is not confused can word function be made optional so = |... or -> |.. so syntax is ever more clearer?
9 people like thisPosted: 8 years ago by Musa Jahanghir
The Eff Monad via delimited continuations, based on http://kcsrk.info/papers/eff_ocaml_ml16.pdf.
2 people like thisPosted: 8 years ago by NIck Palladinos
Translation of the Azure Cosmos DB Graph-get-started sample project (https://github.com/Azure-Samples/azure-cosmos-db-graph-dotnet-getting-started/tree/master/GraphGetStarted) A Cosmos DB account must first be created e.g. via the Azure Portal & from these the endpoint & authorization key are retrieved. Given these, the script creates: (i) Document Client (ii) Database (iii) Graph (aka Document Collection). From Gremlin expressions (strings) the command CreateGremlinQuery creates queries (IDocumentQueries) that can be executed to read from or modify the graph.
9 people like thisPosted: 8 years ago by roguetrainer
SFTP with SSH.Net
4 people like thisPosted: 8 years ago by Tuomas Hietanen
A base class for your view models with methods that take a code quotation of a property to subscribe to, and makes use of IObservable for strongly typed subscriptions to PropertyChanged for this property. You might want to use System.Reactive and insert `Observable.DistinctUntilChanged` after `Observable.map`.
3 people like thisPosted: 8 years ago by Christer van der Meeren
FTPS = SSL encrypted FTP. SFTP = FTP over SSH.
9 people like thisPosted: 8 years ago by Tuomas Hietanen
The Microsoft tutorial Walkthrough: Creating an Asynchronous HTTP Handler did not describe how to use IHttpAsyncHandler from F#.
It was also a bit complicated, because it did not show how to do it from Visual Studio.
Here is the Visual Studio F# version.
1. Create empty ASP.NET Web Application. Call it FSharpHttpAsyncHandler.
2. Add a F# library project to the solution. Call it FSharpHttpAsyncHandler.Lib.
3. Add the following code to Library1.fs in FSharpHttpAsyncHandler.Lib
4. Add a reference to System.Web in FSharpHttpAsyncHandler.Lib
5. Add a reference to FSharpHttpAsyncHandler.Lib in FSharpHttpAsyncHandler.
6. Add the following to Web.config in FSharpHttpAsyncHandler.
7. In the Web tab of the project properties of FSharpHttpAsyncHandler, set Start url to http://localhost:
Posted: 8 years ago by Erling Hellenäs
MailboxProcessor multi reader example
2 people like thisPosted: 8 years ago by Zack
Shows empty list constructor
2 people like thisPosted: 8 years ago by fsoikin
Four colors will print a map so adjacent states have different color. F# has clear concise code. Map has a list of pairs sharing a border. Incremental improvements in the code can be less use of key word 'function'. Since syntax is not ambiguous can it be fixed in the compiler? so '=function |' changes to '=|' ? Welcome to improve. Harrop,Mathias,Jack,Art,HR,fwaris,Don Syme, sffs... Thanks! Musa.Jahanghir@Live.com AVCLive1.com
5 people like thisPosted: 8 years ago by Musa Jahanghir
This is 100% based on tomas petricek blog article. there has been some small additions in regards to adding Result type and handling Monoids for the Writer Part. go check the following blog article : http://tomasp.net/blog/2014/update-monads/ Comment appreciated + bear in mind that performance wise, the Monoid Combine operator, could be greatly improved and more.
3 people like thisPosted: 8 years ago by Fahd Abdeljallal
Get running Visual Studio instances as DTE objects. Based on https://stackoverflow.com/a/14205934
1 people like thisPosted: 8 years ago by Gauthier Segay
To get a fast feedback loop going with web apps, you can run your experiments using the fsi, starting and restarting the web server each time without having to go through a slow msbuild cycle.
4 people like thisPosted: 8 years ago by Chui Tey
A sugar around IEnumerator<'a> to make it nicer to use with recursive functions
5 people like thisPosted: 8 years ago by manofstick
This snippet provides an example of a WPF Event to Command behavior.
4 people like thisPosted: 8 years ago by Daniel Mohl
Small Basic abstract syntax tree, parser and interpreter. Supports Small Basic's keywords and arithmetic, logical and comparison operators.
8 people like thisPosted: 8 years ago by Phillip Trelford
F# Class constructors with wierd behaviour if more then two are present.
3 people like thisPosted: 8 years ago by ChrSt
I couldn't fine a reasonably fast or good (yuck floats) implementation anywhere so I wrote one. All of the error checking does slow it down and should be ideally done up front.
0 people like thisPosted: 8 years ago by Rick Minerich
A little function which generates an infinite sequence consisting of repeats of items from some shorter sequence.
1 people like thisPosted: 8 years ago by Sehnsucht
Can be run in interactive or compiled with FSC. Cobbled together from various other snippets :)
4 people like thisPosted: 8 years ago by asdf
Creates a simple bar chart from a list consisting of a tuple (title:string * value:'a).
1 people like thisPosted: 7 years ago by Tobias Burger
This checks if a string contains all uppercase characters.
5 people like thisPosted: 7 years ago by LuisFX
A simple continuation monad that encodes extensible and type-safe effects.
4 people like thisPosted: 7 years ago by Eirik Tsarpalis
Store rarely accessed efficiently compressed (only for unmanaged types). Efficient decompression with no temporary arrays by utilizing NativePtr with UnmanagedMemoryStream. Uncompressed resultant array stored with WeakReference to save multiple uncompression steps.
4 people like thisPosted: 7 years ago by manofstick
An approach to using annotated types in F# using SRTPs.
4 people like thisPosted: 7 years ago by Eirik Tsarpalis
An approach to using annotated types in F# using overloaded methods.
3 people like thisPosted: 7 years ago by Eirik Tsarpalis
There is another "All Uppercase" snippet that does two searches - one to verify that there's at least one upper case letter and one to make sure there are no lowercase letters. "---D" is "uppercase" but "---" is not. I wanted to duplicate that behavior even though it seems a bit questionable, but do it in one regex search. The underappreciated lookahead features of RegEx allow this sort of thing - scanning forward and then rescanning forward so I use that here
1 people like thisPosted: 7 years ago by Darrell Plank
Computational Expression for Result<'a, 'b>
9 people like thisPosted: 7 years ago by Yuriy Habarov
I recently wrote a program to automatically solve a category of logic puzzles, alone the lines of 'four men walked into a bar, one who drinks Guinness never pays darts...' The objective is to find a unique combination of attributes - name, age, favorite drink, favorite pub activity etc. I decided on a brute force approach, in which I generate every combination of attributes, apply a set of rules, and then inspect for the one unique solution. My solution starts with producing a list of lists of attributes.
0 people like thisPosted: 7 years ago by billhay
I have seen a few postings on the web about this, with not terribly elegant solutions. Here is how I do it.
1 people like thisPosted: 7 years ago by billhay
An active pattern that protects from null reference exceptions stemming from pattern matches on values materialized by .NET libraries such as Newtonsoft.Json
3 people like thisPosted: 7 years ago by Eirik Tsarpalis
Eliminate repetitions in a sequence, preserving the first element in each run of repeats.
2 people like thisPosted: 7 years ago by Kit Eason
A generic, thread-safe version of a MemoryCache based on ConcurrentDictionary, and a memoize function implemented using the MemoryCache.
1 people like thisPosted: 7 years ago by Aaron Eshbach
An exploration of the power of Computation Expressions, Type Extensions, Extension Methods, and Method Overloading. May or may not be a monad or a monoid - we're not sure, nor do we care to check.
7 people like thisPosted: 7 years ago by Tomas Petricek, Krzysztof Cieślak, John Azariah, Phillip Carter
Normally, you'd add two numbers with the '+' operator. But why do that when you can use Type Extensions, custom operations on Computation Expressions, customer operators, and more?
11 people like thisPosted: 7 years ago by Phillip Carter
Emailage email fraud detection query, using https://www.emailage.com/ Supports emails and IPs.
0 people like thisPosted: 7 years ago by Tuomas Hietanen
Generates the authorization header for an OAuth 1.0 enabled service. Tested with Twitter and one other API
1 people like thisPosted: 7 years ago by Faisal Waris
If we can concatenate strings with +, what would it mean to have a / operator?
5 people like thisPosted: 7 years ago by Kit Eason
This is a commonly used algorithm for 'market basket' type analysis. It finds frequent itemsets from a series of transactions. Frequent itemsets are the item combinations that are frequently purchased together. See usage comment for example
0 people like thisPosted: 7 years ago by Faisal Waris
A simple function that sort of emulates the holes feature of Idris for F#
15 people like thisPosted: 7 years ago by Eirik Tsarpalis
A simple abstraction for performing event sourced optimistic transactions
4 people like thisPosted: 7 years ago by Eirik Tsarpalis
When writing asynchronous code in F#, one often needs to call methods in the .NET BCL that return Task or Task
Posted: 7 years ago by Aaron Eshbach
Dependency injection using the cutting edge programming language research, also known as global mutable variable. Is this a serious snippet or not? No category theory and mocking frameworks are required, so probably not.
5 people like thisPosted: 7 years ago by Tomas Petricek
Single-case Discriminated Unions (https://fsharpforfunandprofit.com/posts/designing-with-types-single-case-dus/) are a lightweight way to create types for important concepts in your domain. Unfortunately, there's a few gotchas when consuming from C# to be aware of. For one, if you use the `==` or `!=` operators in C#, it will do a reference comparison, which is almost certainly not what you want for these wrapper types. By overriding `op_Equality` and `op_Inequality`, this will force it to use a structural comparison. Secondly, when using string concatenation via `+`, `String.Format`, or string interpolation, C# will implicitly convert non-string arguments to a string via `ToString`. This means if you forget to use `.Item` to unwrap your value, you will not get a compiler error, it will just implicitly call `ToString`, which by default will look like this: `Id "c148b684-2c40-4383-a1b9-0e8f37752fd0"`. By overriding `ToString`, we can make sure it will look like the raw underlying type when converted to a string: `c148b684-2c40-4383-a1b9-0e8f37752fd0`.
2 people like thisPosted: 7 years ago by Justin Hewlett
This method is described in Knuth's Art of Programming, Volume 3, Page 212. See https://stackoverflow.com/questions/4956593/optimal-algorithm-for-returning-top-k-values-from-an-array-of-length-n This isn't the fastest possible implementation, but it is pure functional code (no mutation).
0 people like thisPosted: 7 years ago by Brian Berns
Usage:
[
Posted: 7 years ago by Yuri Martynov
Executes Async's one by one
0 people like thisPosted: 7 years ago by Yuri Martynov
An F#-style API for simple MSMQ operations, including Peek, Receive, and Send.
3 people like thisPosted: 7 years ago by Aaron Eshbach
F# Functional-style API for MSMQ, providing simple client operations like Send, Receive, and Peek.
3 people like thisPosted: 7 years ago by Aaron Eshbach
Given a location as a float tuple (latitude, longitude) it will return the plane closest nearby as a JsonValue using the OpenSky API. For fun also demonstrating some operator overloading with (-->) between two coordinates. I'm new to these functional languages, so please feel free to update the solution with interesting refactortings and whatnot.
6 people like thisPosted: 7 years ago by Johan Irvall
Not super efficient, and doesn't work on every case, but works most of the time. Json.NET JsonConverter for a JsonValue, i.e. JsonValueConverter. If you're using with a converter for discriminated unions, be sure to give this one higher precedence (since JsonValue is implemented as a DU).
4 people like thisPosted: 7 years ago by Nat Elkins
Easy way to chunk string into equal segments. Returns a list of string chunks (as opposed to an array or seq of chunks).
7 people like thisPosted: 7 years ago by LSM07
Porter Stemmer, please contribute fixes, suggestions, this is merely a syntactic rewrite, I believe though there are some slight mistakes. http://tartarus.org/~martin/PorterStemmer/ ,fixed up endswithdoubleconsonant and endswithocondition
1 people like thisPosted: 7 years ago by David Klein
Async.Start with timeout in seconds
3 people like thisPosted: 7 years ago by Tuomas Hietanen
Bit like http://www.fssnip.net/a7 but send as async.
3 people like thisPosted: 7 years ago by Tuomas Hietanen
Sometimes mailboxprocessor may corrupt on errors and the state is not clear. Sometimes you don't care about the existing queue, but you want to have always a processor listening.
1 people like thisPosted: 7 years ago by Tuomas Hietanen
Takes some HTML, outputs some plaintext. Not tail recursive, not efficient, but got the job done for my use case (had a product feed where the descriptions were HTML, but I needed plaintext).
3 people like thisPosted: 7 years ago by Nat Elkins
The built in foldBack has parameters in an odd order: you can't pipe the array into it, and the folder signature is different from Array.fold's. Here's how to fix it.
6 people like thisPosted: 7 years ago by Kit Eason
Playing around Fable's experimental implicits
3 people like thisPosted: 7 years ago by Evgeniy Andreev
How to enumerate the rational numbers without duplication using a Calkin–Wilf tree.
4 people like thisPosted: 7 years ago by Brian Berns
It is well known that it is impossible to define equality between arbitrary functions. However, there is a large class of functions for which we can determine equality, and it’s strange and surprising. We explore this idea using F# code translated from the Swift programming language.
3 people like thisPosted: 7 years ago by Brian Berns
An example of setting up a MatchEvaluator for use with Regex.Replace in F#.
4 people like thisPosted: 7 years ago by stubel
An event that can defer publication of certain values until a later time, or drop them entirely.
0 people like thisPosted: 7 years ago by Christer van der Meeren
This returns a sequence of union cases for a given discriminated union type, the values in this sequence can be passed into any place that expects a case of that discriminated union. Useful for use as the option values for a combobox, or for printing out all available options for that given discriminated union.
8 people like thisPosted: 7 years ago by Micael Morais
This shows an alternative to using spaces in the discriminated union cases, which makes it harder to write in code, and tends to be needed when interoping with the likes of WPF or any other element that uses the ToString of the union case to display its value. Also useful as an alternative to using special characters like á or ç which make it harder to work with colleagues that don't have keyboards with those characters. Uses code from snippet http://fssnip.net/9l
1 people like thisPosted: 7 years ago by Micael Morais
A generic value converter for discriminated unions, it allows to use a single converter for any discriminated union along with facilitating the creation of new ones with a default option value for when an incompatible union case is provided. Large part of this snippet uses http://fssnip.net/62 as a base, all credit on the ConverterBase goes to him, one of the authors also has a new version of it http://fssnip.net/7Q
1 people like thisPosted: 7 years ago by Micael Morais
ML.Net sentiment classification example using Gradient Boosted trees Needs to be compiled in a dotnet core F# project Uses F# 4.1 struct tuples which is required by the ML.Net API
2 people like thisPosted: 7 years ago by Faisal Waris
ML.Net sentiment classification and cross-validation example using Gradient Boosted trees Needs to be compiled in a dotnet core F# project. Uses F# 4.6 anonymous records which work well with the ML.Net API static api
2 people like thisPosted: 7 years ago by Faisal Waris
A simple function that lets you tail log files on windows
1 people like thisPosted: 7 years ago by Faisal Waris
This snippet declares a function that operates on lists that groups elements of a sequence while the predicate holds. A new group is started for an element when the predicate no longer holds. The predicate is passed the current element and the previous element. This implementation is likely not very efficient.
0 people like thisPosted: 7 years ago by Matthew Rodatus
Adaptation of https://bitbucket.org/rojepp/reflenses/overview using TypeShape
6 people like thisPosted: 7 years ago by Eirik Tsarpalis
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.
3 people like thisPosted: 7 years ago by Jon Harrop
Identify user's browser, Os and device by the browser's UserAgent string.
3 people like thisPosted: 7 years ago by Tuomas Hietanen
This example shows how to add attribute in F# codebase. We use FSharp compiler to get AST, then analyze what we want to change, change it and then combine it back to source code. Example is a little bit naive, it doesn't cover all cases.
1 people like thisPosted: 7 years ago by Ayrat Hudaygulov
I have tested this against the C code I compiled on the PCG website (http://www.pcg-random.org/download.html). It seems to work fine. Nothing special, I just really loathe System.Random. Why has the de-facto RNG for the .NET library not been updated?
3 people like thisPosted: 7 years ago by Krunoslav Saho
Simple (and inaccurate) command line LOC counter mainly for .fs and .fsx files. Extended from: http://www.fssnip.net/b6/title/How-many-lines-of-code-does-your-project-contain Searches current directory and subdirectories (can be changed to only search current dir). Can be changed to whatever filetype is needed. Can be either run as a script (with fsi) or compiled (with fsc).
7 people like thisPosted: 7 years ago by LSM07
Bitcoin transfers. I'm not responsible if your money gets lost. Have fun!
3 people like thisPosted: 7 years ago by Tuomas Hietanen
Parses the schema string format used by the CSV Type Provider from the FSharp.Data library ...because sometimes you need the metadata. Support for names with underscore
5 people like thisPosted: 7 years ago by Faisal Waris
Demonstration of FSI/printer behavior in the presence of ToString and StructuredFormatDisplayAttribute
1 people like thisPosted: 7 years ago by Mark Laws
Like FParsec's pint32, but accepts only optionally-signed base-10 input
1 people like thisPosted: 7 years ago by Mark Laws
Calculate triangle numbers in the most inefficient way possible!
4 people like thisPosted: 7 years ago by Brian Berns
Using WebSharper Remote (Rpc) functions with Azure Functions
1 people like thisPosted: 6 years ago by Abe Mieres
Using WebSharper Remote functions with Azure Functions
4 people like thisPosted: 6 years ago by Abe Mieres
F#'s Choice type is exclusive. The "Both" type defined here allows for the possibility that both values are present. This allows us to zip together sequences of unequal length. Based on Haskell's "These" type and corresponding alignment functions. (See http://hackage.haskell.org/package/these-0.8/docs/Data-These.html and http://hackage.haskell.org/package/these-0.8/docs/Data-Align.html)
1 people like thisPosted: 6 years ago by Brian Berns
Describes a function called "fix" that can be used to generate recursive functions from non-recursive functions, with some simple examples. (Updated with slightly improved comments.)
9 people like thisPosted: 6 years ago by Brian Berns
The snippet shows a minimal example of phantom types for type-safe way of tracking different types of IDs in a simple system.
7 people like thisPosted: 6 years ago by Tomas Petricek
The Luhn algorithm or Luhn formula, also known as the "modulus 10" or "mod 10" algorithm, is a simple checksum formula used to validate a variety of identification numbers, such as credit card numbers.
1 people like thisPosted: 6 years ago by Marnee Dearman
Proof of concept combining HKT encodings à la Higher and object algebras to create a fully type-safe, performant and extensible apparatus for writing generic programs in F#
6 people like thisPosted: 6 years ago by Eirik Tsarpalis
Derived from http://okmij.org/ftp/tagless-final/JFP.pdf
1 people like thisPosted: 6 years ago by Eirik Tsarpalis
Derived from http://okmij.org/ftp/tagless-final/JFP.pdf
3 people like thisPosted: 6 years ago by Eirik Tsarpalis
Uses tagless-final approach for defining abstracted, general purpose computation expression builders.
2 people like thisPosted: 6 years ago by Eirik Tsarpalis
Shows how to use ML.Net AutoML capability for binary classification. Now with progress reporting
2 people like thisPosted: 6 years ago by Faisal Waris
Lightweight HKT encoding using a tiny amount of SRTP constraint solving for assigning the encoding to underlying types
5 people like thisPosted: 6 years ago by Eirik Tsarpalis
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! :)
0 people like thisPosted: 6 years ago by chewie-wookiee
Routine for downloading Yahoo! Finance data as a tuple consisting of a symbol name and data matrix.
0 people like thisPosted: 6 years ago by Dr. Martin Lockstrom
Efficient and elegant way of performing Principal Component Analysis (PCA) in native F# fashion
0 people like thisPosted: 6 years ago by Dr. Martin Lockstrom
Routine for recursively factorize integer numbers
1 people like thisPosted: 6 years ago by Dr. Martin Lockstrom
Simple routines for encrypting/decrypting files using AES
2 people like thisPosted: 6 years ago by Dr. Martin Lockstrom
Simple routines for RSA encryption/decryption
2 people like thisPosted: 6 years ago by Dr. Martin Lockstrom
This one confused me a bit.
2 people like thisPosted: 6 years ago by Phillip Carter
Example that combines generic programming using tagless-final and typeshape for driving folding of arbitrary types.
1 people like thisPosted: 6 years ago by Eirik Tsarpalis
Example that combines generic programming using tagless-final and typeshape for driving folding of arbitrary types.
5 people like thisPosted: 6 years ago by Eirik Tsarpalis
Expression<Func<'a, 'b>> as expr builder
2 people like thisPosted: 6 years ago by habib sadullaev
Fixes http://www.fssnip.net/1K/title/SeqtryTake by moving the enumerator into the `seq` computation and using `use` instead of `let` to dispose the enumerator at the end.
1 people like thisPosted: 6 years ago by Matthias Dittrich
Tries to skip the given number of items and returns the rest. Disposes the enumerator at the end.
3 people like thisPosted: 6 years ago by Matthias Dittrich
A computation expression builder which simplify StringBuilder usage.
6 people like thisPosted: 6 years ago by Sehnsucht
Extensions to the Result module which may be useful for processing Result types.
4 people like thisPosted: 6 years ago by Travis Rosenbaum
Concatenate all the input maps. Where there are duplicate input keys, the last mapping is preserved.
2 people like thisPosted: 6 years ago by Kit Eason
Performs binary search on sorted arrays. Both ascending and descending-ordered arrays are supported. Pass a reverse comparer to the tryBinarySearchWith function to search on descending-ordered arrays.
2 people like thisPosted: 6 years ago by Bang Jun-young
For a given matrix of height H and width W, create a new matrix of height W and width H which is the clockwise rotation of the original matrix.
1 people like thisPosted: 6 years ago by groch
Type-safe Nullable
Posted: 6 years ago by Bang Jun-young
As described in https://en.wikipedia.org/wiki/Harshad_number
1 people like thisPosted: 6 years ago by Tuomas Hietanen
Converting F# LINQ queries to SQL: - Basic example of simple group-by - Also if you want to have multiple aggregates (SUM, COUNT, MAX, MIN, AVG, ...) in the same SQL-clause, that is done with groupBy over a constant value.
2 people like thisPosted: 6 years ago by Tuomas Hietanen
This little snippet shows you how you can create a simple recursive data type and define a pair of functions that maps the set of positive integers to unique instances in the AST and back again.
2 people like thisPosted: 6 years ago by Steve Goguen
Creates a jagged 2d list of Pascal's Triangle.
2 people like thisPosted: 6 years ago by Kayden Tebau
Sort strings as file managers usually do, treating numeric substrings as numbers.
3 people like thisPosted: 6 years ago by Jim Foye
Uses Leibniz equality to generalize an example presented in https://skillsmatter.com/skillscasts/14430-f-sharpunctional-londoners-september
3 people like thisPosted: 6 years ago by Eirik Tsarpalis
Write colored console messages, without them getting intermingled if writing from parallel/async processes.
9 people like thisPosted: 6 years ago by Kit Eason
Demonstrates how to compose code at run time using F# quotations (both typed and untyped) and how to compile and run/execute the quotation using F# Quotations Evaluator (based on F# 2.0 PowerPack code) from the F# Software Foundation. (Updated October 25, 2019)
0 people like thisPosted: 6 years ago by Tomas Petricek, Zane Purvis
This snippet based on Binet's formula combined with fast power algorithm. Four multiplications run in parallel, thus processor with four cores recommended. Bitwise operators improve divisions and multiplications by pow of 2.
0 people like thisPosted: 6 years ago by Pavel Tatarintsev
A simple expression tree visitor, to inject a lambda inside another lambda parameters.
4 people like thisPosted: 6 years ago by Tuomas Hietanen
This snippet is code that solves first Project Euler problem. It finds the sum of all the multiples of 3 or 5 below 1000. Please add other (more efficient, succinct or interesting) solutions to this snippet.
5 people like thisPosted: 6 years ago by Eugene Gavrin
List and calculate and evaluate the polynomials and the expressions for the the derivatives of the powers of trigonometric and hyperbolic sine and cosine.
2 people like thisPosted: 6 years ago by Stijn “Adhemar” Vandamme
Send file via HTML5 with a XMLHttpRequest to WebSharper Sitelet
0 people like thisPosted: 6 years ago by giuliohome
An abstract remoting server API and an abstract web reactive client to call it
0 people like thisPosted: 6 years ago by giuliohome
Calculate the value of Pi, using the Nilakantha series
0 people like thisPosted: 6 years ago by Apurva
Including generic abstraction to manage a RPC call returning either an error or an array of record types from DB server to client browser.
3 people like thisPosted: 6 years ago by giuliohome
Basic wrapper for storing and reading documents from MongoDB with the official .NET driver.
5 people like thisPosted: 6 years ago by Elliot V. Brown
PacMan maze view runnable inside TryFSharp.org
2 people like thisPosted: 6 years ago by Phillip Trelford
Optimizing F# quotations by applying Normalization-by-Evaluation
3 people like thisPosted: 6 years ago by Eirik Tsarpalis
This F# scripts uses PickAll (github.com/gsscoder/pickall) to search the web with Google, DuckDuckGo and Yahoo. Results descriptions are than split to words and counted.
0 people like thisPosted: 6 years ago by Giacomo Stelluti Scala
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 (!)
1 people like thisPosted: 6 years ago by Tomas Petricek
Just an example of a GADT in F#.
1 people like thisPosted: 6 years ago by Bryan Edds
Russian alphabet has 33 letters and since Ё is not frequently used, it makes the perfect candidate for Base32 encoding.
0 people like thisPosted: 6 years ago by Dmitry Achkasov
Creates a random string of length `n` with characters available in `chars` array.
1 people like thisPosted: 6 years ago by Johan Irvall
Playing with coordinates and moves See https://github.com/giuliohome/AdventOfCode2019/blob/master/Day15-Part1-QueueVersion.fs#L54-L66
1 people like thisPosted: 6 years ago by giuliohome
I spent a lot of time this week profiling different permutation functions from various places on the internet. The following was by far the fastest:
8 people like thisPosted: 6 years ago by Rick Minerich
Bitcoin Bech32 address decode / validation - one mutable and one version with fold added.
3 people like thisPosted: 6 years ago by Daniel Hardt
Runs a System.Diagnostics.Process gathering all outputs, timing the run
6 people like thisPosted: 6 years ago by ImaginaryDevelopment
Basic implementation of the continuation monad with explanation.
9 people like thisPosted: 6 years ago by Brian Berns
The random hyperharmonic series is the infinite series S = Sum(1,inf,d(i)/i^pow), where integer pow is greater than 1, and d(i) are independent, identically distributed random variables with property P(d(i)=0) = P(d(i)=1) = 0.5. Cumulative function F(x) = P(S < x) for even powers can be build by combination of analytical and numerical computations.
5 people like thisPosted: 6 years ago by Pavel Tatarintsev
This can be used to generate F# code from an XSD schema. Similar to xsd.exe, this can be wrapped in a console application and used for generator XML or SOAP service clients to facilitate serialization/deserialization of XML into objects.
5 people like thisPosted: 6 years ago by Aaron M Eshbach
Function, what calculates x^n by non-recursive basic exponentiation squaring algorithm. This method uses the bits of the exponent to determine computing powers. Generic parameter x suitable for any type what supports multiplication. I do not suppose existence of inverse operator like "/", thus parameter n must be a positive integer only. It is not difficult to define an extended variant for a type what supports division.
3 people like thisPosted: 6 years ago by Pavel Tatarintsev
Simple prototype C# AST and parser using the FParsec parser combinator library. Parses a subset of C# 1.1 constructs.
8 people like thisPosted: 6 years ago by Phillip Trelford
String.Join (" ", [| "This" ; "is"; "a" ; "way" ; "to" ; "generate" ; "a" ; "shuffled" ; "array" ; "with" ; "given" ; "elements" ; "from" ; "an" ; "(ordered)" ; "array." |]) |> printf "\n >> %A\n"
1 people like thisPosted: 5 years ago by you
"Please enter the description" - Why'd I do that ?
4 people like thisPosted: 5 years ago by you
This program is a mess, really - just ignore support functions. It'll be great if you can help me tidy up. Here's the passcode: "Passcode". The version of code below may not be original.
3 people like thisPosted: 5 years ago by you
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 this solution. In order to send SMS messages from your ASP.NET application, you need a development platform, e.g 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! :)
2 people like thisPosted: 5 years ago by Aarav Gupta
Why do my functions work "properly" with int8, int16, ... float64, decimal but not with string and bigInt ?
6 people like thisPosted: 5 years ago by me
Sometimes you need to take more elements from a sequence, e.g. look at https://stackoverflow.com/questions/12562327/how-to-do-seq-takewhile-one-item-in-f This solution allows fetching elements from the same sequence after applying takeWhile, skip, take and other sequence functions. However, need to remember to call function with right parameter: use 'true' to include current element into result sequence (after takeWhile for example)
2 people like thisPosted: 5 years ago by Ruslan Enikeev
You might have heard that a "free" monad can be created from any functor. Unfortunately, that doesn't mean much if you're not already familiar with category theory. This example creates a free monad from a simple functor types
5 people like thisPosted: 5 years ago by Brian Berns
Configure Argu to read from hosted Microsoft.Extensions.Configuration and pass a ParseResult<'T> through dependency injection.
This allows you to combine Argu's full-featured command-line handling and strong typing with M.E.C's multiple sources (appSettings.
Posted: 5 years ago by Loïc Denuzière
Configure Argu to read from hosted Microsoft.Extensions.Configuration and pass a ParseResult<'T> through dependency injection.
This allows you to combine Argu's full-featured command-line handling and strong typing with M.E.C's multiple sources (appSettings.
Posted: 5 years ago by Loïc Denuzière
Simple implementation of the Sieve of Eratosthenes with set arithmetic.
3 people like thisPosted: 5 years ago by galacticdessert
Showcasing fssnip's support for the latest F# and .NET Core
5 people like thisPosted: 5 years ago by Eirik Tsarpalis
A good use case for demonstrating the use of active patterns
6 people like thisPosted: 5 years ago by Faisal Waris
A minimal async builder applicatives example. Also showcases fssnip support for F# preview language features.
8 people like thisPosted: 5 years ago by Eirik Tsarpalis
Convert a list of tuples into a crosstab of key with list of values with that key
4 people like thisPosted: 5 years ago by Steve Channell
In Windows you can press WindowsKey & dot to open Emoji menu.
8 people like thisPosted: 5 years ago by Tuomas Hietanen
invokes op_Implicit when applied (for implicit conversions). I have found this to be very convenient when using C# libraries
6 people like thisPosted: 5 years ago by Faisal Waris
With .NET Core 3 a template 'dotnet new worker' was created that allows services to be created. The template currently only works to create C# code so this snippet shows how I have translated the C# into F# and the steps needed to create the service.
dotnet new console -lang F# -o FsharpService
cd FsharpService
dotnet add package Microsoft.Extensions.Hosting.WindowsServices
dotnet add package System.Net.NameResolution
Update the program.fs as shown below and then build and install the service
dotnet publish -r win-x64 -c Release /p:PublishSingleFile=true /p:PublishTrimmed=true -o "./published"
sc create fSharpService binPath= "<
Posted: 5 years ago by Jackson McCann
Based on Tomas Petricek's: http://fssnip.net/a7 .
Shows how to handle non OK (200) response codes, where .Net raises an exception upon GetResponse(), which makes it difficult to recover further error information. Here the snippet shows how to handle errors wrapping a Result
Posted: 5 years ago by Joan Arnaldich
When playing rock-paper-scissors (RPS), we show 0 fingers for rock, 2 for scissors and 5 for paper. This rule is also applied for this console-based game written in F#. Enjoy !
0 people like thisPosted: 5 years ago by me
Function that associates a time window with each element of a sequence. The resulting sequence can then be grouped by the time windows for further processing
3 people like thisPosted: 5 years ago by Faisal Waris
Using phantom types to emulate simple dependent types and sized list. Inspired by: https://www.seas.upenn.edu/~sweirich/cis670/09/
6 people like thisPosted: 5 years ago by Vankata
Inspired by https://10print.org, this is a small incomplete BASIC interpreter that can generate a maze.
5 people like thisPosted: 5 years ago by Tomas Petricek
Uses SRTPs to define a general purpose adapter for awaiting arbitrary C# awaitables in F# async workflows.
4 people like thisPosted: 5 years ago by Eirik Tsarpalis
Read-only STRtree backed by NetTopologySuite.Spatial.Index.STRTree
2 people like thisPosted: 5 years ago by Swoorup Joshi
Left join (2 maps) and inner join (3 maps)
4 people like thisPosted: 5 years ago by Swoorup Joshi
Reverse unicode string, who may contains surrogate pairs
2 people like thisPosted: 5 years ago by Enrico Sada
Initial example of using PKCS#11 from F#
1 people like thisPosted: 5 years ago by Tuomas Hietanen
A simple example of how to define a custom type that enforces extra business rules by using a single-case discriminated union with a private constructor
7 people like thisPosted: 5 years ago by Tomas Petricek
A quick snippet showing three different ways of dynamically/reflectively locating a module then invoking a generic function. The first two don't rely on a class. But the third is more readable/understandable for most .NET devs.
5 people like thisPosted: 5 years ago by Cerberus (FSharp Discord)
Needed to receive an OAuth 2 response so used simple http listener
3 people like thisPosted: 5 years ago by Ivan Rainbolt
Returns the index of the first element in the sorted array that does not compare less than 'target'. The given method returns an option type to handling non matching cases. parameters: target - The value whose lower bound has to be found arr - sorted array beg - start index, usually zero en - end index, usually length of array minus one
0 people like thisPosted: 5 years ago by Krishna Mohan
Contains operations for working with 2-dimensional lists.
3 people like thisPosted: 5 years ago by Pavel Tatarintsev
We can use active patterns for parsing values of types with defined TryParse methods.
6 people like thisPosted: 5 years ago by Evgeniy Andreev
Nested recursive loop which has certain uses cases for loop optimization when you don't want to traverse across entire ranges but rather subsets incrementally and decrementally etc.
2 people like thisPosted: 5 years ago by Martin Lockstrom
Updated to use the new "nuget:..." style references. At this time a workaround is needed to properly load some of the native libraries.
1 people like thisPosted: 5 years ago by Faisal Waris
This snippet features an F# Web crawler that i'm already using in 2 applications (slightly modified). It's based on a scalable network of communicating agents that follow URLs extracted from HTML pages until reaching the specified limit.
8 people like thisPosted: 5 years ago by Taha Hachana
Replicate an AsyncSeq n-ways. The consumption rate of the resulting consumers are kept in check against each other so that a single consumer does not race too far ahead
3 people like thisPosted: 5 years ago by Faisal Waris
There is a namespace System.Runtime.Serialization.Json To serialize generic object you can do like this...
7 people like thisPosted: 5 years ago by Tuomas Hietanen
A useful pattern for I/O heavy or view-less apps. User defines an order type to use instead of Cmd<'msg> and an "execute" function processing said orders and dispatching message. It frees the update function from command code, centralizes I/O in a elmishy way and exempts from the Cmd module. Inspired by the CmdMsg pattern, see: https://fsprojects.github.io/Fabulous/Fabulous.XamarinForms/update.html#replacing-commands-with-command-messages-for-better-testability
6 people like thisPosted: 5 years ago by Julien Di Lenarda
Plot the vector field v = ( y, -x ) using FSharp.Plotly
2 people like thisPosted: 5 years ago by AutoLolita
Solve Ordinary Differential Equation Newton's Law of Cooling Chart using Plotly The object will eventually reach room temperature after a period of time
4 people like thisPosted: 5 years ago by AutoLolita
Calculates progressive tax on an annual income.
2 people like thisPosted: 5 years ago by Ujjawal Sinha
I'm bad at math and writing this code down helped me to understand what's up with this counter intuitive problem.
4 people like thisPosted: 5 years ago by Julien Di Lenarda
An infinite lazy list of primes. Not efficient, but elegant and fun.
4 people like thisPosted: 5 years ago by Brian Berns
Simple helper to ease building xml with XElement and XAttribute in F#
3 people like thisPosted: 5 years ago by Vianney PHILIPPE
This example shows how to use .env files together with the awesome command line parsing capabilities of Argu.
2 people like thisPosted: 5 years ago by toburger
Demonstrates the minimum references required to run an AspNet.Core web server in F# script
4 people like thisPosted: 4 years ago by Chui Tey
This is a recursive active pattern for extracting the elements of a list quotation as a list of Exprs, There doesn't seem to be a List pattern in the standard library. The compiler will complain about this recursive pattern unless you use #nowarn "40".
4 people like thisPosted: 4 years ago by allisterb
This is the solution of a homework the son of a friend had to solve during homeschooling and he asked a couple of his friends on how to solve the following problem: Given a kickboard has three rolls and a city roller has two rolls we want to know *how many kickboards and how many city rollers are parked*. We know two things: * The sum of all the rolls combined is 37 * There are 15 rollers (kickboards and rollers) parked Now being a developer I wanted to solve it via programming. :-D I've used the Decider library which allows you to formulate and solve the problem as following.
3 people like thisPosted: 4 years ago by toburger
Recursive function for converting byte array to binary string
2 people like thisPosted: 4 years ago by Martin Lockstrom
Every spot in the puzzle belongs to a (horizontal) row and a (vertical) column, as well as to one single 3x3 square (which we call "square" for short). At the beginning, some of the spots carry a single-digit number between 1 and 9. The problem is to fill the missing spots with digits in such a way that every number between 1 and 9 appears exactly once in each row, in each column, and in each square.
3 people like thisPosted: 4 years ago by Tomas Petricek
Extracts text content from PDF file using PDFsharp.
3 people like thisPosted: 4 years ago by Phillip Trelford
A line-by-line translation of Norvig's original Python code. An attempt to view F# as a "typed" Python.
0 people like thisPosted: 4 years ago by Nick Palladinos
ContextAwareTask implementation from https://github.com/dotnet/Nerdbank.GitVersioning/blob/master/src/Nerdbank.GitVersioning.Tasks/ContextAwareTask.cs
2 people like thisPosted: 4 years ago by anthony-mi
Assembly resolver implementation required by .NET Framework MSBuild task to resolve different versions of assembly because of missing binding redirect functionality in MSBuild.
5 people like thisPosted: 4 years ago by anthony-mi
A simple example showing how to use Quartz.NET, an open source job scheduling system, with FSharp.
1 people like thisPosted: 4 years ago by Taha Hachana
This module extracts all the 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.
0 people like thisPosted: 4 years ago by devshorts
Procedurally generates a sheet of invader graphics
2 people like thisPosted: 4 years ago by Phillip Trelford
these `Seq` functions allow to split and process Seqs in a sequential manner without the need to rescan or cache elements into memory.
2 people like thisPosted: 4 years ago by Abelardo Mieres
Solve a sample problem from the book "Think Bayes" by Allen B. Downey. Shows how the problem can be modeled with Infer.Net and also provide the manual solution as presented in the book. The code relies on the Infer.Net "FSharpWrapper" project which is not included in the nuget package (as of now).
4 people like thisPosted: 4 years ago by Faisal Waris
get all combinations (as array index values) with k items from n items. indexes are 1 based
0 people like thisPosted: 4 years ago by snuup
Active pattern returning list of captured groups with parsing.
0 people like thisPosted: 4 years ago by Evgeniy Andreev
The ASCII wave renderer behind https://goq2q.net/blog/tech/using-ascii-waveforms-to-test-real-time-audio-code
7 people like thisPosted: 4 years ago by John Wostenberg
Convenient CEs that allow you to measure how long it takes to execute a given content.
5 people like thisPosted: 4 years ago by Natalie Perret
Extension of Plotly.NET to draw Sankey diagrams by leveraging the underlying capability offered by Plotly.js
1 people like thisPosted: 4 years ago by Faisal Waris, Tobias Burger
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.
2 people like thisPosted: 4 years ago by Vandroiy
Sketch of a Zio like monad in F# for computations with extensible environment, extensible error handling, and asynchronicity.
1 people like thisPosted: 4 years ago by Vesa Karvonen
F# utility functions for Option, Result, and others. Adapted to .NET 6.0
4 people like thisPosted: 4 years ago by Ruxo Zheng
The code snippet for working with Windows Forms DatagridView with filtering and sorting features.
2 people like thisPosted: 4 years ago by Vladimir Demydov
The text file containing proxies named "proxlist.txt", in the form of "ip:port" per line is the input source, the program will attempt to establish a connection through each proxy to a provided URL. Proxies that passed the test will be written out to the file "results.txt" in the form "ip:port duration_of_connection_attempt"
2 people like thisPosted: 4 years ago by Vladimir Demydov
Shuffle an array
2 people like thisPosted: 4 years ago by Josh DeGraw
Fast Sudoku solver in less than 100 lines of F#
6 people like thisPosted: 4 years ago by Faisal Waris
Fizz
4 people like thisPosted: 4 years ago by Evgeniy Andreev
Push-relabel algorithm for Max Flow problems in flow graphs. (Does not check if graph has improper back edges)
3 people like thisPosted: 4 years ago by Faisal Waris
a debounce function for F# Fable
4 people like thisPosted: 4 years ago by Daniel Hardt
Another version of QuickSort implementation.
6 people like thisPosted: 4 years ago by Shankar V
Fold it!
1 people like thisPosted: 4 years ago by Evgeniy Andreev
Now with nice syntax!
0 people like thisPosted: 4 years ago by Evgeniy Andreev
Build strings using powerful higher-rank encoding!
0 people like thisPosted: 4 years ago by Evgeniy Andreev
IT'S IMPOSSIBLE TO WRITE PRODUCTION CODE WITHOUT TYPE CLASSES
1 people like thisPosted: 4 years ago by Evgeniy Andreev
A version of AsyncSeq.groupBy where the user can synchronously request all groups, but also all elements in each group during iteration and the operation does not deadlock.
0 people like thisPosted: 4 years ago by Tomas Petricek
Computation expression that automatically captures the rest of the sequence that you are iterating over using a "for" loop so that the exception handler can do something clever with it.
0 people like thisPosted: 4 years ago by Tomas Petricek
A basic implementation.
0 people like thisPosted: 4 years ago by Julien Di Lenarda
(Please ignore previous entry of the same name)
0 people like thisPosted: 4 years ago by Julien Di Lenarda
Neat trick to improve safety
3 people like thisPosted: 4 years ago by Evgeniy Andreev
We can use power of computation expressions and InlineIfLambda to get nice syntax and mutable index tracking for allocating strings
3 people like thisPosted: 4 years ago by Evgeniy Andreev
Flappy bird clone script using WinForms, click the mouse or hit space to flap, no collision detection.
6 people like thisPosted: 4 years ago by Phillip Trelford
PGP F# with PGPCore https://blog.bitscry.com/2018/07/05/pgp-encryption-and-decryption-in-c/
0 people like thisPosted: 4 years ago by Tuomas Hietanen
This F# code decrypts an encrypted string using Rijndael symmetric encryption algorithm. It uses key and initialization vector stored in a registry key.
2 people like thisPosted: 4 years ago by Tuomas Hietanen
Self-contained module for scripting or small console programs.
7 people like thisPosted: 3 years ago by Pim Brouwers
Request throttling based on a time span and a request count. An `IDistributedCache` implementation is used which integrates nicely into ASP.NET Core. E.g. you can throttle requests from a specific IP address to allow fifty requests within a period of thirty seconds at most.
3 people like thisPosted: 3 years ago by toburger
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.
0 people like thisPosted: 3 years ago by ImaginaryDevelopment
A small set of operators for converting boolean expressions to an optional type on the principle of false -> None, true -> Some value.
0 people like thisPosted: 3 years ago by Pavel Tatarintsev
Binary tree traversal with continuation passing style transformation and defuntionalization
0 people like thisPosted: 3 years ago by tathanhdinh
An tail recursive implementation of insertion sort on list
0 people like thisPosted: 3 years ago by tathanhdinh
This rotates or shifts a list. Unlike http://www.fssnip.net/qY/title/Rotate-List, which runs exponentially, this runs at O(n). In case of overflow (i.e., shift index is larger than the size of the list) will run at most once more with the modulo. This is done to prevent using `List.length` prior to entering the function, as that would lead to a perf punishment of an extra O(n) on each invocation. For large lists, `shift largeList 1` would then get a big performance hit.
1 people like thisPosted: 3 years ago by Abel Braaksma
F# Impletementation of StringBuilderCache
1 people like thisPosted: 3 years ago by Pim
This snippet provides a builder for scope {...} computational workflow that returns a Scope object implementing System.IDisposable interface. All "use" bindings inside scope {...} workflow are kept from being disposed immediately when computation leaves scope. Instead, they are disposed only when resulting Scope object is disposed. This makes possible to access disposable outside the scope while it remains usable. This can be achieved by via return statement of workflow that can return, for example, a closure that encapsulates disposable. scope {...} return value is available through Value property of Scope object. Scopes may be nested through let! binding that means that nested scope will be disposed when the resulting scope is disposed.
3 people like thisPosted: 3 years ago by Crazy Monk
One of the 99 OCaml problems rewritten in F#
7 people like thisPosted: 3 years ago by Vladimir Khorikov
The snippet shows how to use Microsoft Chart Controls (available in .NET 4.0 and for .NET 3.5) to draw a Doughnut chart. The sample shows proportion of seats taken by parties in UK elections.
6 people like thisPosted: 3 years ago by Tomas Petricek
There are some nuances to using the regular expression type provider that are easy to miss. This snippet addresses them.
7 people like thisPosted: 3 years ago by musicologyman
Fibonacci function to calculate population after a given number of months (n) and mortality (m)
7 people like thisPosted: 3 years ago by Luke Limpert
Inserts a space every 3 characters in a string starting from the end of the string.
1 people like thisPosted: 3 years ago by shazmodan
Starts at a given position. Using any kind of "tag" like <%replaceThis%> with something corresponding from the Map.
0 people like thisPosted: 3 years ago by shazmodan
Starts at a given position. Using any kind of "tag" like <%replaceThis%> with something corresponding from the Map.
0 people like thisPosted: 3 years ago by shazmodan
Use a regular expression to find all groups of three digits before the decimal point. Returns the modified string.
3 people like thisPosted: 3 years ago by shazmodan
Makes a single Websocket request and waits for the first response
4 people like thisPosted: 3 years ago by Fave Oled
Find binding-redirects with linq-to-xml from a .config file. This might be useful for then parsing config-changes e.g. by System.Linq.Enumerable.Except
4 people like thisPosted: 3 years ago by Tuomas Hietanen
Sample to estimate and visualize kernel densities of multiple distributions for visual comparison. Here the distributions of NY taxi fares are being compared by payment type (e.g. cash, credit card, etc.)
1 people like thisPosted: 3 years ago by Faisal Waris
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
2 people like thisPosted: 3 years ago by Faisal Waris
Sort collection of items based on criteria of closest distance between consecutive items. The resulting collection first element is one of two farthest items, the end element is the second of the farthest pair. For the collection of `n` items the distance function is called n*(n-1) /2 times. The distance for pair of items is assumed to not depend on items order.
2 people like thisPosted: 2 years ago by Konstantin Sh
Compiles simple F# quoted expressions (literals, values, operators, ifs and for loops) to Java code.
2 people like thisPosted: 2 years ago by Phillip Trelford
Overlapping chunks from a sequence - a mix of 'windowed' and 'chunkBySize'. Useful for chopping up sequences for a variety of time-domain analysis tasks (re-write to remove deprecated F# syntax)
1 people like thisPosted: 2 years ago by Faisal Waris
Some of the standard higher-order functions (like Seq.map, Seq.iter, Seq.filter) but implemented for Excel interop. Effortlessly iterate across ranges of cells, reading them, updating them or formatting them. NB. Type-information won't be displayed correctly on fssnip (Office not installed on server presumably), so to get this working paste the code into VS, make yourself a spreadsheet with a range called 'MyRange' and use FSI to explore.
2 people like thisPosted: 2 years ago by Kit Eason
This snippet shows how to create a WPF custom control library in F#.
4 people like thisPosted: 2 years ago by Fahad
The snippet extends a web crawler from snippet http://fssnip.net/3K. It synchronizes all printing using an additional agent (so printed text does not interleave) and the crawling function returns an asynchronous workflow that returns when crawling completes.
0 people like thisPosted: 2 years ago by Tomas Petricek
Demonstrates how to use unfold to create a sequence of fibonacci numbers
5 people like thisPosted: 2 years ago by Dave Yost
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.
6 people like thisPosted: 2 years ago by Russ Cam
High-performance JSON parsing with System.Text.Json and F#
2 people like thisPosted: 2 years ago by Tuomas Hietanen
The example uses Seq.splitBy and Seq.tryHeadTail twice to split the input file in two and then into several pieces collecting the output file names in the first section and the content in the subsequent pieces It can efficiently split a huge 2.2GB file into several subfiles without having to rescan the file or cache in memory any portions of the file apart from the current line.
5 people like thisPosted: 2 years ago by amieres
A function that will take a sequence of directory names and return a sequence of all file names within.
5 people like thisPosted: 2 years ago by Shankar Velayudhan
Stubbed methods for a computation expression with some explanations
7 people like thisPosted: 2 years ago by Jimmy Byrd
76a9142220867b1e79c403fafe339a809a65ed01cb697988ac
8 people like thisPosted: 2 years ago by The streets
An example showing how to process list in a pipeline. We first use List.filter to return only even numbers and then use List.map to format them as strings.
4 people like thisPosted: 1 year ago by Tomas Petricek
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.
7 people like thisPosted: 1 year ago by Tuomas Hietanen
Interactive computation that asks the user questions
9 people like thisPosted: 1 year ago by Tomas Petricek
Pseudoword generator based on code from Evan Fosmark circa 2009.
0 people like thisPosted: 1 year ago by Phillip Trelford
Uses StringBuilder to achieve performance.
2 people like thisPosted: 1 year ago by shazmodan
Higher-order functions for working with nested lists that reimplement various useful List module functions, but work on nested lists, preserving the original nesting strucutre when possible.
4 people like thisPosted: 1 year ago by Tomas Petricek
Just use the concat
0 people like thisPosted: 1 year ago by Tuomas Hietanen
Exemplary convenience wrappers for some of the System.
Posted: 1 year ago by Cody
An implementation of minimal adaptive cells
0 people like thisPosted: 1 year ago by Onur Gumus
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.
0 people like thisPosted: 11 months ago by Phillip Trelford
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.
2 people like thisPosted: 11 months ago by Tuomas Hietanen
Word guessing game using ASCII art.
3 people like thisPosted: 10 months ago by Phillip Trelford
Timestamp: Time format in ISO 8601 with timezone. YYYYMMDDhhmmssffff+zzzz For example 2011-05-17 19:01:10.000 -0200 would be: 20110517190110000-0200
0 people like thisPosted: 9 months ago by Tuomas Hietanen
A functional wrapper around MailboxProcessor that simplifies agent-based concurrency, adds error handling via events, and provides convenience functions to avoid common pitfalls when working with asynchronous message processing in F#.
2 people like thisPosted: 7 months ago by halcwb
Example of shaping an anonymous-object-as-JSON structure for an Azure dashboard using strong typing and minimal code using Farmer F# https://compositionalit.github.io/farmer/
3 people like thisPosted: 6 months ago by Tuomas Hietanen
Takes a list of (quantity/amount and price/rate) as decimals, and gives a weighted average
1 people like thisPosted: 6 months ago by Tuomas Hietanen
ModelContextProtocol with FSharp (MCP with F#) https://modelcontextprotocol.io/docs/getting-started/intro Client and Server examples using https://github.com/modelcontextprotocol/csharp-sdk
2 people like thisPosted: 6 months ago by Tuomas Hietanen
Download and install Ollama: https://ollama.com/ Ollama is a free common host for multiple different LLM-models like Google Gemma, OpenApi's GPT-OSS, Deepseek, etc.
2 people like thisPosted: 6 months ago by Tuomas Hietanen
Pong video game runnable inside fable.io. Controls are "A" for left, and "D" for right.
8 people like thisPosted: 3 months ago by Phillip Trelford
令人愉快的 旅游信息网站, 继续发展 充满灵感。感谢!
4 people like thisPosted: 2 months ago by 方尖碑