Snippets in category Functional Programming
Filtering lists
Two functions showing how to filter functional lists using the specified predicate. First version uses naive recursion and the second one is tail-recursive using the accumulator parameter.
39 people like this
Posted: 1 years ago by Tomas PetricekProjecting lists
Three functions showing how to implement projection for functional lists. First version uses naive recursion and the second one is tail-recursive using the accumulator parameter. The third version extends this with continuation passing.
43 people like this
Posted: 1 years ago by Tomas PetricekHello world (F#)
Classical "Hello world" example that prints a message to the console output. This version uses F# printfn function to do the printing.
131 people like this
Posted: 1 years ago by Tomas PetricekHello world (.NET)
Classical "Hello world" example that prints a message to the console output. This version uses .NET Console.WriteLine method to do the printing.
23 people like this
Posted: 1 years ago by Tomas PetricekPipeline list processing
An example showing how to process list in a pipeline. We first use List.filter to return only even numbers and then use List.map to format them as strings.
76 people like this
Posted: 1 years ago by Tomas PetricekUnfolding Sequences
Demonstrates how to use unfold to create an infinite list of the fibonacci numbers
39 people like this
Posted: 1 years ago by Robert PickeringUsing the 'lazy' Keyword
This snippet uses the lazy keyword to create a delayed computation. It then show's using 'force' to evaluate the computation.
23 people like this
Posted: 1 years ago by Robert PickeringUsing the 'lazy' Keyword
Demonstrates using the 'lazy' keyword. Show's how a lazy value will only ever be evaluated once.
42 people like this
Posted: 1 years ago by Robert PickeringUnfolding Sequences
Show's using the unfold function to create a sequence that terminates once some limit is passed.
25 people like this
Posted: 1 years ago by Robert PickeringComposing a list of functions
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".]
59 people like this
Posted: 1 years ago by NovoxContinuation-Passing Mnemonics
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.
64 people like this
Posted: 1 years ago by Neil Carrierelements of 3 value tuple
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.
22 people like this
Posted: 1 years ago by daniel szymanskiWinForms layout combinators
A domain specific language for creating layout using Windows Forms. The snippet implements combinators for creating controls and simple automatic arrangement of them.
17 people like this
Posted: 1 years ago by Tomas PetricekA beautiful fixed-point finding function
We start with an initial value and then applying f repeatedly, until the value does not change anymore.
164 people like this
Posted: 1 years ago by Nick PalladinosMemoization and Tail Recursive Function
Hi, I expressed Memoization and Memoization Tail Recursive on the functions. I hope something useful.
12 people like this
Posted: 1 years ago by zeclTree searching using Tail recursion with continuation
Sample code which demonstrate tree searching using : Tail recursion with continuation
9 people like this
Posted: 1 years ago by Ankur DhamaActive 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 PetricekUri Parser
A Uri parser using the Cashel library [1]. This implementation is using ArraySegment<byte> as the underlying state, as I'm using it within a server, but it would be trivial to switch it to using a list. Also, note that I am not parsing the Uri into any specific structure, though that, too, would be trivial. For my current purposes, I just needed to validate the Uri. [1] https://github.com/panesofglass/cashel
20 people like this
Posted: 1 years ago by Ryan RileyDisposable 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 PetricekFunctional wrappers for TryParse APIs
Exemplary convenience wrappers for some of the System.<Typename>.TryParse APIs, using the combined power of F#' return value deconstruction mechanism via pattern matching, active patterns and option types instead of "out/ref" parameters
15 people like this
Posted: 1 years ago by NovoxInspect middle of a pipeline in VS 2010 debugger
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.
32 people like this
Posted: 1 years ago by Oldrich SvecCaching the function object created
Caching the function object created
13 people like this
Posted: 1 years ago by fholmStruct Tuple
Two/Three/Four-element generic tuples implemented as a value types for writing more efficient F# code.
47 people like this
Posted: 1 years ago by fholmAbstracting over 'M'
A higher kind of request to Don Syme... please please please,,,, we desperately need higher kinds!
13 people like this
Posted: 1 years ago by Nick PalladinosUnion constructors can be used as functions
Union constructors can be used as functions
13 people like this
Posted: 1 years ago by fholmSmall embedded DSL to write in F# "Who is John Galt?"
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.
18 people like this
Posted: 1 years ago by Horacio NuñezA Lazy fixed-point combinator
x = f(x) encoded in F#
14 people like this
Posted: 1 years ago by Nick PalladinosCurry / Uncurry
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
30 people like this
Posted: 1 years ago by Carsten KönigZipMap
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
17 people like this
Posted: 1 years ago by Carsten KönigMonadic Memoization
Modular memoization within a pure functional setting that is implemented as a convenient computation builder.
56 people like this
Posted: 1 years ago by Nick Palladinossum the nodes in a (not-binary) tree using continuations
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.
21 people like this
Posted: 1 years ago by Carsten KönigFunctor => Applicative => Monad
Yet another attempt of mine to "haskellify" my F# coding.
8 people like this
Posted: 1 years ago by Nick PalladinosIRC Jokes
Simple snippet that demonstrates recursively defined discriminated unions, the Y combinator (for encoding recursive functions) and recursive processing of tree-like structures
5 people like this
Posted: 1 years ago by Daniel JacksonHow to write a financial contract
Implements the theory from 'How to write a financial contract' by S.L Peyton Jones and J-M Eber
7 people like this
Posted: 1 years ago by Ademar GonzalezLazy String
Lazy string based on seq<char>
4 people like this
Posted: 1 years ago by Ankur DhamaThe repmin problem
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.
1 people like this
Posted: 1 years ago by Nick PalladinosRed-Black-Trees with insert
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
4 people like this
Posted: 1 years ago by Carsten KönigA fun-ny WPF DataTemplate DSL
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.
5 people like this
Posted: 11 months ago by Cetin SertMiss Grant's Controller
State machine example, from Martin Fowler's Domain-Specific Languages book, implemented as an Internal DSL in F#. The semantic model is implemented with F# discriminated unions. A custom operator (=>) specifies state transitions from events. Finally mutually recursive functions define the state machine.
Miss Grant's Controller Parser
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.
6 people like this
Posted: 11 months ago by Phillip TrelfordFunctions not so first class in active patterns
It seems that you can't pass anonymous functions as parameters to active patterns.
3 people like this
Posted: 11 months ago by Kurt SchelfthoutF# Future using lazy and a threading event
F# Future using lazy and a threading event. Supports creating futures from functions or asyncs. Eager evaluation of can be specified.
3 people like this
Posted: 11 months ago by Ankur Dhama
Functional Unparsing SQL
A combinator based DSL for composing type-safe parameterized sql queries. Inspired by Olivier Danvy's "Functional Unparsing" paper.
8 people like this
Posted: 10 months ago by Nick PalladinosRepeat until
Repeatedly call a function until it returns a positive result. Implemented using sequences.
2 people like this
Posted: 10 months ago by Johann DeneuxmemoizeBy
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 this
Posted: 10 months ago by Rick MinerichLazyBuilder
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 zeclIteratee
An iteratee based on https://john-millikin.com/software/enumerator/ and http://okmij.org/ftp/Haskell/Iteratee/IterateeIO-talk-notes.pdf
6 people like this
Posted: 10 months ago by Ryan RileyTiny IO Monad
Haskell-style IO in F#.
6 people like this
Posted: 10 months ago by igetaTurtle
Turtle graphics library implemented as an internal DSL, providing a very similar syntax to Logo, it is runnable inside TryFSharp.org.
5 people like this
Posted: 10 months ago by Phillip TrelfordSeq.reduceBallanced function
The function has the same type as Seq.reduce. Instead of reducing elements from the left to the right, it splits the input into two halves, reduces each half separately and then aggregates the results using the given function. This means that the values are aggregated into a ballanced tree, which can save stack space.
2 people like this
Posted: 9 months ago by Tomas PetricekIterateeCPS
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 this
Posted: 9 months ago by Ryan RileyContinuation Monad with Call/CC
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.
3 people like this
Posted: 9 months ago by Ryan RileyCoroutine
An implementation of Coroutine by using a continuation monad. it's using a monad library [1]. [1] https://github.com/fsharp/fsharpx
3 people like this
Posted: 8 months ago by einblickerDelimited 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 einblickerCall/CC for Async
An implementation of call-with-current-continuation for Async.
2 people like this
Posted: 8 months ago by Ryan RileyMonadic Retry
A Monad for composing computations with retry logic. (Useful when we work with Cloud Services)
6 people like this
Posted: 7 months ago by Nick PalladinosLazy variable
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 this
Posted: 6 months ago by NobuhisaMemoization for dynamic programming
The snippet shows how to implement reusable memoization function and how to use it to implement efficient Fibonacci number generator using dynamic programming.
1 people like this
Posted: 6 months ago by Tomas PetricekSemi-Coroutine
This snippet implements a semi-coroutine by continuations.
2 people like this
Posted: 6 months ago by einblickerNon-deterministic computation builder
Computation builder for writing non-deterministic computations.
7 people like this
Posted: 6 months ago by Tomas PetricekMake a chain of functions
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.
26 people like this
Posted: 5 months ago by Tao LiuStarbucks
Simple DSL for describing cups of Starbucks coffee and computing prices (in dollars).
7 people like this
Posted: 5 months ago by Phillip TrelfordLight XML DSL
A light domain specific language for declaring xml in F# as code.
4 people like this
Posted: 5 months ago by Huw SimpsonDSL for financial contracts
Simple domain-specific language (DSL) for describing financial contracts in F#. A contract is represented using a discriminated union. Evaluating a contract gives the orders that may happen at a given date.
6 people like this
Posted: 5 months ago by Tomas PetricekSimple typeclass implementation
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.
2 people like this
Posted: 5 months ago by nagat01n-ary Seq.map
A pattern for creating n-ary Seq.map functions.
2 people like this
Posted: 4 months ago by Nick Palladinosn-ary Seq.map (Numerals)
A pattern for creating n-ary Seq.map functions, based on numerals.
2 people like this
Posted: 4 months ago by Nick PalladinosCircular Buffer
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.
4 people like this
Posted: 3 months ago by Ryan RileySimple sql command helper
Minimalist assistant to read data / execute database command.
4 people like this
Posted: 3 months ago by S. KasperovichPolymorphic 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 DaniilException 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 KoganLazy Xml
A Lazy Xml structure for processing large xml documents.
6 people like this
Posted: 1 months ago by Nick PalladinosExpression parsing with monads
Compositional expression parsing with monads. https://bitbucket.org/ZachBray/parsad
4 people like this
Posted: 1 months ago by Zach BrayJSON parsing with monads
JSON parsing with monads. See also "Expression parsing with monads" (http://fssnip.net/bi). Author URL: http://www.zbray.com
5 people like this
Posted: 1 months ago by Zach BrayTesco in 70 lines of code
Domain model for the Tesco checkout implemented in F# using discriminated unions (in 20 lines of code) and console-based user interface for scanning products and calculating the total price.
3 people like this
Posted: 1 months ago by Tomas PetricekFinalizing Tesco purchase
The sample shows two different reprezentations of Tesco checkout. The first one stores scanned items - as a list of either purchase or cancel items - and the second stores final bill with product and total quantity. The snippet implements transformation that corresponds to finalizing the purchase.
3 people like this
Posted: 1 months ago by Tomas PetricekSimple 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 HietanenSimple builder example: Nullable
Simple Computational expressions / monad / builder -example, using .NET Nullable as demo.
3 people like this
Posted: 28 days ago by Tuomas HietanenClassifier DSL
sample
Classifier DSL Setup
Classifier DSL Setup
DSL for Financial Contracts
Simple domain-specific language for modeling of financial contracts.
6 people like this
Posted: 27 days ago by Tomas PetricekDSL for Price Patterns (Setup)
Domain-specific language for detecting patterns in stock prices. Run using try F#.
3 people like this
Posted: 27 days ago by Tomas PetricekDSL for Price Patterns (Demo)
Examples that use domain-specific langauge for detecting price patterns. To run the sample, load the previous snippet in TryF#. It opens the sample automatically.
2 people like this
Posted: 27 days ago by Tomas PetricekTraits, 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