Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Itertools for F#

Tags:

itertools

f#

I'm used to Python's itertools for doing functional things with iterators (F#: sequences) and wondered if there were equivalents in F# or a commonly used library since they're so handy.

The top tools for me are:

  • product : cartesian product, equivalent to a nested for-loop
  • combinations
  • permutations
  • takewhile
  • dropwhile
  • chain : chain multiple iterators together into a new longer iterator
  • repeat* : repeat(5) -> 5, 5, 5...
  • count* : count(10) -> 10, 11, 12...
  • cycle* : cycle([1,2,3]) -> 1,2,3,1,2...

* I suppose these 3 would yield monads in F#? How do you make them infinite?

I'm prompted to ask because I saw this question on permutations in F# and was surprised it was not part of a library or built into the language.

like image 668
Phil H Avatar asked Apr 11 '13 23:04

Phil H


People also ask

What is Itertools function in Python?

Itertools is a module in Python, it is used to iterate over data structures that can be stepped over using a for-loop. Such data structures are also known as iterables. This module works as a fast, memory-efficient tool that is used either by themselves or in combination to form iterator algebra.

Is Itertools faster than for loops?

That being said, the iterators from itertools are often significantly faster than regular iteration from a standard Python for loop.

How do I use Itertools in Python 3?

The itertools. combinations() function takes two arguments—an iterable inputs and a positive integer n —and produces an iterator over tuples of all combinations of n elements in inputs . >>> list(it. combinations(bills, 3)) [(20, 20, 20), (20, 20, 10), (20, 20, 10), ... ]


1 Answers

I don't know if there's a commonly used library that contains functions like product, combinations and permutations, but the others you've mentioned are already in Seq and List modules or can be implemented without much trouble, and there are also useful methods in System.Linq.Enumerable.

  • takewhile -> Seq.takeWhile
  • dropwhile -> Seq.skipWhile
  • chain -> Seq.concat
  • repeat -> Seq.initInfinite
  • count(10) -> Seq.initInfinite ((+) 10)
  • cycle([1, 2, 3]) -> Seq.concat <| Seq.initInfinite (fun _ -> [1; 2; 3])

You also might want to check out the excellent FSharpx library -- it contains a lot of useful functions to work with collections and whatnot.

like image 109
MisterMetaphor Avatar answered Oct 05 '22 05:10

MisterMetaphor