Snippets in category F# language

  • Hello world (.NET)

    Classical "Hello world" example that prints a message to the console output. This version uses .NET Console.WriteLine method to do the printing.

    23 people like this
    Posted: 1 years ago by Tomas Petricek

  • 'use' Bindings

    Show's how to use F# 'use' key word to dispose a resource when it passes out of scope.

    24 people like this
    Posted: 1 years ago by Robert Pickering

  • Using Active patterns

    Shows how to use an active pattern that will try to determine the format of an input value.

    10 people like this
    Posted: 1 years ago by Robert Pickering

  • Using Active patterns

    Show's how to create a parametrized active pattern that will match based on a regular expression.

    15 people like this
    Posted: 1 years ago by Robert Pickering

  • Units of Measure

    Show's how to define units of measure to add stronger typing to your numerical functions.

    52 people like this
    Posted: 1 years ago by Robert Pickering

  • Nice formatting of type names

    Add extension to System.Type that returns the name of type including generic arguments in a nice readable format. It returns only short names of generic type and type arguments.

    13 people like this
    Posted: 1 years ago by Tomas Petricek

  • Support slicing operator

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

    37 people like this
    Posted: 1 years ago by Tomas Petricek

  • Compiling quotations

    Demonstrates how to compose code at run time using F# quotations (both typed and untyped) and how to compile and run the quotation using F# PowerPack API.

    40 people like this
    Posted: 1 years ago by Tomas Petricek

  • Creating objects with events

    This snippet shows how to create objects with events in F#. It shows both simple event (to be used from F#) and a .NET compatible event with specific delegate type.

    53 people like this
    Posted: 1 years ago by Tomas Petricek

  • Working with paths

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

    9 people like this
    Posted: 1 years ago by Tomas Petricek

  • Traverse quotation

    Shows how to use the 'ExprShape' module to recursively traverse an entire quotation and how to write quotation transformations. As an example, the snippet replaces all numeric constants in the quotation and then runs the transformed code.

    13 people like this
    Posted: 1 years ago by Tomas Petricek

  • Dictionary extensions

    Extensions to dictionaries.

    21 people like this
    Posted: 1 years ago by Ryan Riley

  • inline pow

    LanguagePrimitives help create inline functions

    23 people like this
    Posted: 1 years ago by Dmitri Pavlenkov

  • Create generic IEnumerable from non-generic

    Depends on Castle Dynamic Proxy 2. Returns an IEnumerable<T> from a System.Type and a System.Collections.IEnumerable. It is a hack I wrote simply because I couldn't find anything in the framework to do this.

    19 people like this
    Posted: 1 years ago by Dan Finch

  • Inline factorial samples with fix point

    While reading Tomas Petricek's master thesis, came across FIX operator implementation. Decided to experiment with various implementations of factorial.

    10 people like this
    Posted: 1 years ago by Dmitri Pavlenkov

  • Supercompilation using quotations

    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.

    16 people like this
    Posted: 1 years ago by Dmitry Soshnikov

  • Playing with async sequences

    Attempt to reimplement functions AsyncRead/AsyncReadLines from 'Rx on the server ' articles (by Jeffrey van Gogh) using idea of AsyncSequence (by Tomas Petricek)

    18 people like this
    Posted: 1 years ago by Vladimir Matveev

  • Active pattern for let binding inside patterns

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

    49 people like this
    Posted: 1 years ago by Tomas Petricek

  • Regular expression active pattern

    Active pattern returning list of captured groups.

    7 people like this
    Posted: 1 years ago by Daniel Robinson

  • Exiting cleanly

    Demonstrates how to run a function when the user presses Ctrl+C, closes the console window, or logs off.

    29 people like this
    Posted: 1 years ago by Tim Robinson

  • Find verbose .NET types using Reflection

    Searches all (currently loaded) types using Reflection to find the types with longest and shortest names of members. Uses average length of all type member names as a metric.

    8 people like this
    Posted: 1 years ago by Tomas Petricek

  • Disposable computation builder

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

    27 people like this
    Posted: 1 years ago by Tomas Petricek

  • Read only ref

    F# implementation of RO_ref from the "Effective ML" talk.

    74 people like this
    Posted: 1 years ago by fholm

  • Caching the function object created

    Caching the function object created

    13 people like this
    Posted: 1 years ago by fholm

  • Extensions to the Fold function

    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)

    22 people like this
    Posted: 1 years ago by Horacio Nuñez

  • Perl Style "Regex Matches?" operator

    Perl Style "Regex Matches?" operator

    35 people like this
    Posted: 1 years ago by fholm

  • Enumerator computation builder

    The snippet defines computation builder for working with IEnumerator. The bind operation (let!) reads next element from the enumerator, so the computation can be used for expressing things that cannot be written just using seq.

    25 people like this
    Posted: 1 years ago by Tomas Petricek

  • WPF Custom Control

    This snippet shows how to create a WPF custom control library in F#.

    30 people like this
    Posted: 1 years ago by Fahad

  • Byte literals

    Demonstrates an array initialized from byte literals, which use the 'uy' suffix, and an array initialized from a string byte array literal

    27 people like this
    Posted: 1 years ago by Tim Robinson

  • Simple asynchronous functions

    The snippet demonstrates how to compose simple asynchronous functions and how to use try .. with to handle exceptions in asynchronous workflows.

    28 people like this
    Posted: 1 years ago by Tomas Petricek

  • Manage Variable Length Dictionary Entries

    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

    2 people like this
    Posted: 1 years ago by Brendan Campbell

  • Imperative computation builder

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

    6 people like this
    Posted: 1 years ago by Tomas Petricek

  • Resource cleanup event combinator

    Declares an event combinator 'Event.using' that automatically releases resources allocated by a previous event occurence. Each event occurence creates a value using a function specified by the user and automatically calls 'Dispose' when generating a new value.

    2 people like this
    Posted: 1 years ago by Tomas Petricek

  • Use of Partial-Case with Parameters

    Depicts use of one kind of active pattern matching; partial-case with parameters.

    5 people like this
    Posted: 1 years ago by Joel Huang

  • High precedence, right associative backward pipe

    High precedence, right associative backward pipe

    4 people like this
    Posted: 1 years ago by Stephen Swensen

  • Fun with polynoms and inline

    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 this
    Posted: 1 years ago by Carsten König

  • palindromes

    Find every substring that is a palindrome. A bit lazier than the original.

    0 people like this
    Posted: 1 years ago by Kevin Cantu

  • Async SNTP client

    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.

    8 people like this
    Posted: 1 years ago by Joel Mueller

  • .NET Interop

    Facilities for interop with languages supporting null.

    3 people like this
    Posted: 1 years ago by Daniel Robinson

  • General power function with units

    The snippet demonstrates how to write a general power function that has correct type involving units-of-measure. The function uses numbers represented using types. The snippet is mainly an example of what can be done (not recommended for the real world).

    5 people like this
    Posted: 1 years ago by Tomas Petricek

  • sscanf - parsing with format strings

    A more complete version of sscanf, as proposed on stackoverflow by kvb: http://stackoverflow.com/questions/2415705/read-from-console-in-f

    7 people like this
    Posted: 1 years ago by Wolfgang Meyer

  • Computation Builder for Cartesian Products

    Sample framework for computing Cartesian products using a computation builder.

    7 people like this
    Posted: 1 years ago by TechNeilogy

  • Abstraction of the "tail-recursive loop" pattern

    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 this
    Posted: 1 years ago by Stephen Swensen

  • F# Quotations with INotifyPropertyChanged

    ViewModelBase for F# users who want to use it in WPF / Silverlight

    6 people like this
    Posted: 1 years ago by Fahad

  • Ref Example

    Deferencing the ref FinalAnswer inside a let produces different results than using !FinalAnswer directly. Why?

    0 people like this
    Posted: 12 months ago by

  • Check if value is a valid enum or flags combination

    -

    1 people like this
    Posted: 12 months ago by Daniel Robinson

  • Structural BeginUpdate / EndUpdate with Lambda

    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.

    2 people like this
    Posted: 12 months ago by Stephen Swensen

  • Active pattern for comparison

    An active pattern for comparing two objects of the same type and implementing IComparable. Modeled on Standard ML comparison.

    4 people like this
    Posted: 11 months ago by petebu

  • Active pattern to define default values

    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.

    7 people like this
    Posted: 11 months ago by Kurt Schelfthout

  • Quotation property name + comp + value extract

    for zec_ on irc

    0 people like this
    Posted: 11 months ago by fholm

  • Improved map declaration

    Ruby like map declaration syntax

    6 people like this
    Posted: 10 months ago by Saagar Ahluwalia

  • LazyBuilder

    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.

    8 people like this
    Posted: 10 months ago by zecl

  • Tiny IO Monad

    Haskell-style IO in F#.

    6 people like this
    Posted: 10 months ago by igeta

  • Get COM instances from Running Object Table

    Type extensions for System.Activator which enable the retrieval of COM instances from the Running Object Table.

    1 people like this
    Posted: 10 months ago by Huw Simpson

  • raiseAfterHandlers

    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 this
    Posted: 10 months ago by Sebastian Good

  • Permutation and Combination

    Permutation and Combination using ListBuilder.

    8 people like this
    Posted: 9 months ago by zecl

  • Universal Type

    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 this
    Posted: 9 months ago by Ademar Gonzalez

  • Clumsy LoopBuilder

    Clumsy LoopBuilder.It's mischievous trick.

    4 people like this
    Posted: 8 months ago by zecl

  • Delimited Continuation Monad

    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

    3 people like this
    Posted: 8 months ago by einblicker

  • Creating observable using Async.StartDisposable

    Implements a simple Async.StartDisposable extension that can be used to easily create IObservable values from F# asynchronous workflows. The method starts an asynchronous workflow and returns IDisposable that cancels the workflow when disposed.

    4 people like this
    Posted: 8 months ago by Tomas Petricek

  • Clojure-like lambda function syntax

    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.

    4 people like this
    Posted: 7 months ago by einblicker

  • Another tennis implementation

    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/

    2 people like this
    Posted: 6 months ago by Colin Bull

  • Non-deterministic computation builder

    Computation builder for writing non-deterministic computations.

    7 people like this
    Posted: 6 months ago by Tomas Petricek

  • Active pattern to extract HttpStatusCode from WebException

    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.

    5 people like this
    Posted: 5 months ago by Leaf Garland

  • Enum -> MVC3 SelectList

    Converts an Enum to a Selectlist which can be used by a @Html.DropDownList

    10 people like this
    Posted: 4 months ago by christophd

  • XNA's Vector3 with units of measure

    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.

    7 people like this
    Posted: 4 months ago by Johann Deneux

  • Using units of measure for safe array access

    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.

    6 people like this
    Posted: 4 months ago by Johann Deneux

  • Heterogeneous container

    OCaml original here : http://eigenclass.org/R2/writings/heterogeneous-containers-in-ocaml

    7 people like this
    Posted: 4 months ago by Ademar Gonzalez

  • Transform expressions into Excel formulae

    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"

    14 people like this
    Posted: 4 months ago by Natallie Baikevich

  • Peano constructs

    Here we define Peano arithmetic using F# abstract data types.

    4 people like this
    Posted: 3 months ago by Daniil

  • Ninety-Nine F# Problems - Problems 1 - 10 - Lists

    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 this
    Posted: 3 months ago by Cesar Mendoza

  • Ninety-Nine F# Problems - Problems 11 - 20 - List, continued]

    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 this
    Posted: 3 months ago by Cesar Mendoza

  • Ninety-Nine F# Problems - Problems 21 - 28 - Lists again

    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 this
    Posted: 3 months ago by Cesar Mendoza

  • Ninety-Nine F# Problems - Problems 31 - 41 - Arithmetic]

    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 this
    Posted: 3 months ago by Cesar Mendoza

  • Ninety-Nine F# Problems - Problems 46 - 50 - Logic and Codes

    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 this
    Posted: 3 months ago by Cesar Mendoza

  • Ninety-Nine F# Problems - Problems 54 - 60 - Binary trees

    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.

    2 people like this
    Posted: 3 months ago by Cesar Mendoza

  • Ninety-Nine F# Problems - Problems 61 - 69 - Binary trees

    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.

    2 people like this
    Posted: 3 months ago by Cesar Mendoza

  • Ninety-Nine F# Problems - Problems 70 - 73 - Multiway Trees

    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 this
    Posted: 3 months ago by Cesar Mendoza

  • Ninety-Nine F# Problems - Problems 80 - 89 - Graphs

    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 this
    Posted: 3 months ago by Cesar Mendoza

  • Ninety-Nine F# Problems - Problems 90 - 94 - Miscellaneous problems]

    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.

    2 people like this
    Posted: 3 months ago by Cesar Mendoza

  • Ninety-Nine F# Problems - Problems 95 - 99 - Miscellaneous problems]

    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 this
    Posted: 3 months ago by Cesar Mendoza

  • Higher-Order Functions for Excel

    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.

    5 people like this
    Posted: 2 months ago by Kit Eason

  • Polymorphic Maybe monad with default value.

    Polymorphic (via generics) Maybe monad/computational expression with default value + Zipper

    4 people like this
    Posted: 2 months ago by Daniil

  • Sierpinski triangle, WPF

    Draws a Sierpinski triangle using WPF

    8 people like this
    Posted: 2 months ago by Mathias Brandewinder

  • Exception Retry Computation Expression

    Retry monad: chaining functions together, retrying each one if exceptions are thrown, until the first time a function can no longer be retried

    2 people like this
    Posted: 2 months ago by Boris Kogan

  • In-place parallel QuickSort

    It's fairly straightforward in-place QuickSort implementation which uses ThreadPool for parallelization. Still slower than library function Array.sortInPlace, though.

    3 people like this
    Posted: 1 months ago by Lakret

  • Expanding quotations

    The snippet implements a function "expand" that takes a quotation and performs two operations. It replaces all calls to methods marked with ReflectedDefinition with the body of the method and it simplifies all expressions that can be reduced in call-by-name style (let binding & application of lambda).

    1 people like this
    Posted: 1 months ago by Tomas Petricek

  • Simple NumericLiteral example

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

    4 people like this
    Posted: 29 days ago by Tuomas Hietanen

  • Simple builder example: Nullable

    Simple Computational expressions / monad / builder -example, using .NET Nullable as demo.

    3 people like this
    Posted: 28 days ago by Tuomas Hietanen

  • How to check whether an F# function/method has been initialized

    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 this
    Posted: 8 days ago by ZackZhou

  • Traits, Mixins and Aspect-Oriented Programming in F#

    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.

    11 people like this
    Posted: 5 days ago by Zach Bray

  • F# yet another Interop example

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

    5 people like this
    Posted: 4 days ago by David Klein

  • How to Serialize Record, Discriminated Union and Tuple in Azure?

    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/13524

    0 people like this
    Posted: 43 mins ago by AndrewXue