May 06, 2014 Simple matching on a range | ||||
---|---|---|---|---|
| ||||
Is it a good idea to add a function like this to Phobos? This is just a first draft of the idea. void main() { import std.stdio, std.algorithm, std.range, range_matcher; auto primes = iota(2, uint.max) .filter!(x => iota(2, x) .all!(t => x % t != 0)); auto twinPrimes = primes.rangeMatch!(q{x, x + 2}, q{ [x, x + 2] }); twinPrimes.take(20).writeln; immutable arr = [1, 2, 1, 3, 5, 3]; // All items of arr that appear twice or more: arr.rangeMatch!(q{x, $_, x}, q{ x }).writeln; } Output: [[3, 5], [5, 7], [11, 13], [17, 19], [29, 31], [41, 43], [59, 61], [71, 73], [101, 103], [107, 109]] [1, 3] rangeMatch takes three arguments, the first is a range of items. The second is a string that encodes what to match, and the third is a string that generates the output from the matched data. So q{x, x + 2} matches any value x followed by x + 2. This is the definition of twin prime, if the input sequence is of primes. q{x, $__, x} matches any x, followed by 1 or more other items, followed by the same x. $_ means 0 or more. Bye, bearophile |
Copyright © 1999-2021 by the D Language Foundation