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:
* 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.
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.
That being said, the iterators from itertools are often significantly faster than regular iteration from a standard Python for loop.
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), ... ]
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With