Snippets in category Sequences

  • Random walk

    Create sequence of floating point values generated by random walk process. Functional solution using sequence expressions and yield! construct in a tail-call position.

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

  • Unfolding 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 Pickering

  • Unfolding 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 Pickering

  • Random Walk

    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.

    28 people like this
    Posted: 1 years ago by James

  • Largest Palindrome Number from Product of Two Three Digit Numbers

    Here is an improved version twice shorter, than original

    35 people like this
    Posted: 1 years ago by Nick Canzoneri

  • Sequence Random Permutation

    A generic function that randomly permutes the elements of a sequence.

    29 people like this
    Posted: 1 years ago by Taha Hachana

  • Haskell function : iterate

    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.

    102 people like this
    Posted: 1 years ago by Nick Palladinos

  • Cartesian Product of Sequences

    Computes the Cartesian product of a sequence of sequences. See corresponding example for a list of lists.

    31 people like this
    Posted: 1 years ago by Neil Carrier

  • 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

  • Asynchronous sequences

    An asynchronous sequence is similar to the seq<T> type, but the elements of the sequence are generated asynchronously without blocking the caller as in Async<T>. This snippet declares asynchronous sequence and uses it to compare two files in 1k blocks.

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

  • Break sequence into n-element subsequences

    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.

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

  • EnumerableStream

    A lazy enumerable/stream of bytes.

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

  • Fibonacci sequence

    Cached fib sequence

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

  • Partition a sequence until a predicate is satiated

    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.

    38 people like this
    Posted: 1 years ago by Rick Minerich

  • Seq.tryTake

    A more tolerant and open-minded take.

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

  • Function to generate circular infinite sequence from a list

    Function to generate circular infinite sequence from a list

    12 people like this
    Posted: 1 years ago by Ankur Dhama

  • Take every Nth element of sequence

    A function that takes every Nth element of a sequence where N is passed as an argument. The snippet shows a naive function and a function using IEnumerator directly to provide an efficient implementation.

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

  • Project Euler #182

    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<e<phi, such that gcd(e,phi)=1. There exist values of e and m such that m^(e) mod n=m. We call messages m for which m^(e) mod n=m unconcealed messages. Choose p=1009 and q=3643. Find the sum of all values of e, so that the number of unconcealed messages for this value of e is at a minimum.

    20 people like this
    Posted: 1 years ago by Natallie Baikevich

  • Example of annoying enumeration syntax

    Example of annoying enumeration syntax

    11 people like this
    Posted: 1 years ago by fholm

  • Seq.unsort

    Randomizes order of specified sequence

    21 people like this
    Posted: 1 years ago by Phillip Trelford

  • Palindromic dates

    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.

    12 people like this
    Posted: 1 years ago by Francesco De Vittori

  • Abstract Console.ReadLine as an infinite sequence

    Abstracts console input as an infinite sequence of strings

    7 people like this
    Posted: 1 years ago by fholm

  • Farey Sequence

    Return a sequence that contains the numerators and denominators as tuples for Farey Sequence n.

    1 people like this
    Posted: 1 years ago by Graham Spiers

  • 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

  • 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

  • Gaussian Random Sequence

    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.

    32 people like this
    Posted: 1 years ago by Tony Lee

  • Chronological sequence window beginnings

    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 )

    10 people like this
    Posted: 1 years ago by ildjarn

  • Restartable File.ReadLines

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

    32 people like this
    Posted: 1 years ago by Tony Lee

  • List Comprehensions with float iterator

    Is it a bug or a feature? :)

    1 people like this
    Posted: 1 years ago by Oldrich Svec

  • Typed access to IEnumerable

    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.

    6 people like this
    Posted: 1 years ago by kvb

  • Lazy String

    Lazy string based on seq<char>

    4 people like this
    Posted: 1 years ago by Ankur Dhama

  • A failed attempt at evaluating sequence items in terms of a try-with block

    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 this
    Posted: 1 years ago by Rick Minerich

  • Partition a sequence into groups linearly by predicate

    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)

    0 people like this
    Posted: 1 years ago by Rick Minerich

  • Very Fast Permutations

    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:

    4 people like this
    Posted: 1 years ago by Rick Minerich

  • Tree using sequences

    Tree implementation using sequences.

    2 people like this
    Posted: 1 years ago by Ankur Dhama

  • Seq.filter with accumulator

    Seq.filter with accumulator, without using mutable or ref.

    1 people like this
    Posted: 1 years ago by Ankur Dhama

  • exec with redirected io as sequences

    Since F# is my new scripting language, I needed something like Perl's exec but with sequences for Std In and Out.

    5 people like this
    Posted: 1 years ago by Tony Lee

  • Seq.partition

    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.

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

  • Moving Average

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

    7 people like this
    Posted: 12 months ago by Brett V. Forsgren

  • Check if value is a valid enum or flags combination

    -

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

  • Seq.triplewise

    Triple version of Seq.pairwise.

    1 people like this
    Posted: 12 months ago by ptan

  • Select n elements in group from seq

    Select n elements in group from seq

    1 people like this
    Posted: 12 months ago by Ankur Dhama

  • Incremental (Functional) QuickSort

    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.

    2 people like this
    Posted: 11 months ago by Tony Lee

  • Hughes's FuncList

    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 this
    Posted: 11 months ago by Nick Palladinos

  • Sequence Generator from Async

    Generates a sequence using a sequence generator and Async.StartWithContinuations. This is an attempt at modeling the OWIN delegate structure in F#

    4 people like this
    Posted: 11 months ago by Ryan Riley

  • Hughes's CPSFuncList

    A CPS version of FuncList, in order to avoid blowing the stack.

    3 people like this
    Posted: 11 months ago by Nick Palladinos

  • Reading a collection of records from database

    This snippet can be used to read all records from a given table and expose them as an IEnumerable<T> (seq)

    3 people like this
    Posted: 11 months ago by Eduardo Claudio

  • Moving average

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

    4 people like this
    Posted: 11 months ago by Paul Papathomas

  • All subsets of a set

    A function implemented using sequence expressions that returns all subsets of a specified set. The function is not optimized, but it is very easy to understand.

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

  • Seq.sumBy implemented in terms of Seq.fold

    Seq.sumBy implemented in terms of Seq.fold

    2 people like this
    Posted: 11 months ago by ildjarn

  • Repeat until

    Repeatedly call a function until it returns a positive result. Implemented using sequences.

    2 people like this
    Posted: 10 months ago by Johann Deneux

  • Iteratee

    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 Riley

  • Seq group continuous matching elements

    Seq group continuous matching elements [1;1;1;2;2;2] will become [ [1;1;1] ; [2;2;2] ]

    2 people like this
    Posted: 10 months ago by Ankur Dhama

  • Split sequences

    Split sequences based on a predicate.

    1 people like this
    Posted: 10 months ago by Ankur Dhama

  • Seq.groupWhen function

    The snippet declares a function that groups adjacent elements of a sequence. A new group is started when the specified predicate holds about an element. Groups are constructed eagerly (using lists).

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

  • ByteString

    An initial attempt at creating a ByteString type based on the Haskell version.

    1 people like this
    Posted: 10 months ago by Ryan Riley

  • Splice sequence into other sequence

    Splices a sequence into another sequence at a specified index n. Can replace the existing element at n or keep it.

    3 people like this
    Posted: 9 months ago by Henrik Ravn

  • Soundex Algorithm

    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 this
    Posted: 9 months ago by Matt Wilson

  • Take value from a sequence only when it changes

    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]

    0 people like this
    Posted: 9 months ago by Ankur Dhama

  • JoinList

    A JoinList is a variation on the list type that offers a constant time append operation.

    5 people like this
    Posted: 9 months ago by Ryan Riley

  • Seq.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 Petricek

  • Finding matching pairs in two sequences

    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 this
    Posted: 9 months ago by Kit Eason

  • IterateeCPS

    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 Riley

  • Euler #5

    Euler #5 solution

    3 people like this
    Posted: 8 months ago by Michael Falanga

  • Calculating when the 1000th XKCD will appear

    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

    2 people like this
    Posted: 8 months ago by Robert Pickering

  • Gluing-up sequence members

    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 this
    Posted: 8 months ago by Gene Belitski

  • Yet another command-line parser

    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.

    2 people like this
    Posted: 7 months ago by Gennady Loskutov

  • Seq.groupAfter function

    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 this
    Posted: 6 months ago by Thorsten Meinecke

  • Random Subset

    A function that takes a random subset from a seq<'T>.

    0 people like this
    Posted: 5 months ago by Taha Hachana

  • n-ary Seq.map

    A pattern for creating n-ary Seq.map functions.

    2 people like this
    Posted: 4 months ago by Nick Palladinos

  • n-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 Palladinos

  • Nest items of a sequence

    A function that nests items of a sequence that do not match a specified predicate under the last item that matches the predicate. The input is a sequence of values and the result is a sequence of pairs where the second element is a list of nested items.

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

  • Generate a repeating infinite sequence

    A little function which generates an infinite sequence consisting of repeats of items from some shorter sequence.

    1 people like this
    Posted: 3 months ago by Kit Eason

  • Transform a sequence into a sequence-of-sequences

    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.

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

  • Take a sample of a sequence

    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, with possibly a shorter interval at the end if the sequence length is not evenly divisible by the sample size.

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

  • Sierpinski triangle, WPF

    Draws a Sierpinski triangle using WPF

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

  • tryNth

    Computes the nth value of a sequence if the nth value is past the length of the sequence then None is returned else some

    2 people like this
    Posted: 4 days ago by Colin Bull