Itertools for F#

f#, python-itertools

Solution

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.

Problem

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.

Original source