{ $subsections zip zip-as }
"Creating an assoc from key/value sequences and their indices:"
{ $subsections zip-index zip-index-as }
+"Creating an assoc from a sequence and a key quotation:"
+{ $subsections zip-with zip-with-as }
"Creating key/value sequences from an assoc:"
{ $subsections unzip }
;
}
{ $description "Zip a sequence with its index and return an associative list of type " { $snippet "exemplar" } " where the input sequence is the keys and the indices are the values." } ;
-{ unzip zip zip-as zip-index zip-index-as } related-words
+HELP: zip-with
+{ $values
+ { "seq" sequence } { "quot" { $quotation ( ... key -- ... value ) } }
+ { "alist" assoc }
+}
+{ $examples
+ { $example "USING: assocs math prettyprint ;"
+ "{ 1 2 3 4 } [ sq ] zip-with ."
+ "{ { 1 1 } { 2 4 } { 3 9 } { 4 16 } }"
+ }
+}
+{ $description "Zip a sequence with values generated by applying " { $snippet "quot" } " to each element in the sequence." } ;
+
+HELP: zip-with-as
+{ $values
+ { "seq" sequence } { "quot" { $quotation ( ... key -- ... value ) } }
+ { "exemplar" assoc } { "assoc" assoc }
+}
+{ $examples
+ { $example "USING: assocs math prettyprint ;"
+ "{ 1 2 3 4 } [ sq ] H{ } zip-with-as ."
+ "H{ { 1 1 } { 2 4 } { 3 9 } { 4 16 } }"
+ }
+}
+{ $description "Zip a sequence with values generated by applying " { $snippet "quot" } " to each element in the sequence, outputting an " { $link assoc } " of type " { $snippet "exemplar" } "." } ;
+
+{ unzip zip zip-as zip-index zip-index-as zip-with zip-with-as } related-words
HELP: collect-by
{ $values
V{ { 11 0 } { 22 1 } { 33 2 } }
} [ { 11 22 33 } V{ } zip-index-as ] unit-test
+! zip-with, zip-with-as
+{
+ { { "cat" 3 } { "food" 4 } { "is" 2 } { "yummy" 5 } }
+} [
+ { "cat" "food" "is" "yummy" } [ length ] zip-with
+] unit-test
+
+{
+ H{ { "cat" 3 } { "food" 4 } { "is" 2 } { "yummy" 5 } }
+} [
+ { "cat" "food" "is" "yummy" } [ length ] H{ } zip-with-as
+] unit-test
+
{
H{
{ 0 V{ 0 3 6 9 } }
: unzip ( assoc -- keys values )
dup assoc-empty? [ drop { } { } ] [ >alist flip first2 ] if ;
+: zip-with-as ( ... seq quot: ( ... key -- ... value ) exemplar -- ... assoc )
+ [ [ keep swap ] curry ] dip map>assoc ; inline
+
+: zip-with ( ... seq quot: ( ... key -- ... value ) -- ... alist )
+ { } zip-with-as ; inline
+
: collect-by ( ... seq quot: ( ... obj -- ... key ) -- ... assoc )
[ keep swap ] curry H{ } clone [
[ push-at ] curry compose each