May 15, 2011 [Issue 6004] New: std.range.unzip() | ||||
---|---|---|---|---|
| ||||
http://d.puremagic.com/issues/show_bug.cgi?id=6004 Summary: std.range.unzip() Product: D Version: D2 Platform: All OS/Version: All Status: NEW Severity: enhancement Priority: P2 Component: Phobos AssignedTo: nobody@puremagic.com ReportedBy: bearophile_hugs@eml.cc --- Comment #0 from bearophile_hugs@eml.cc 2011-05-15 05:15:06 PDT --- In Python and Haskell there is a way to invert the operation of zip(), this is a commonly used feature/function: Python (V2.6.6): >>> s = "abc" >>> d = [1, 2, 3] >>> z = zip(s, d) >>> z [('a', 1), ('b', 2), ('c', 3)] >>> zip(*z) [('a', 'b', 'c'), (1, 2, 3)] Haskell (GHCI v.7.0.2): Prelude> let s = "abc" Prelude> let d = [1, 2, 3] Prelude> let z = zip s d Prelude> z [('a',1),('b',2),('c',3)] Prelude> unzip z ("abc",[1,2,3]) A D example shows where it's useful: import std.stdio, std.typecons, std.algorithm, std.range; Tuple!(int,int) divMod(int n, int m) { return tuple(n / m, n % m); } void main() { auto r = map!((m){ return divMod(20,m); })(iota(1, 20)); int[] firsts, seconds; foreach (t; r) { firsts ~= t[0]; seconds ~= t[1]; } writeln(firsts); writeln(seconds); } Output: [20, 10, 6, 5, 4, 3, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1] [0, 0, 2, 0, 0, 2, 6, 4, 2, 0, 9, 8, 7, 6, 5, 4, 3, 2, 1] Similar code in Python shell: >>> r = (divmod(20, m) for m in xrange(1,20)) >>> firsts, seconds = zip(*r) >>> firsts (20, 10, 6, 5, 4, 3, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1) >>> seconds (0, 0, 2, 0, 0, 2, 6, 4, 2, 0, 9, 8, 7, 6, 5, 4, 3, 2, 1) In Phobos a higher-order function to perform this operation may be named "unzip" as in Haskell. This unzip is generalizable to zips of more than two sequences: unzip(zip([1,2,3], "abc", [0.5,1.0,1.5])) -- Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email ------- You are receiving this mail because: ------- |
Copyright © 1999-2021 by the D Language Foundation