% This LaTeX document was generated using the LaTeX backend of PlDoc, % The SWI-Prolog documentation system \section{library(pairs): Operations on key-value lists} \label{sec:pairs} \begin{tags} \tag{author} Jan Wielemaker \tag{See also} \predref{keysort}{2}, \file{library(assoc)} \end{tags} This module implements common operations on Key-Value lists, also known as \textit{Pairs}. Pairs have great practical value, especially due to \predref{keysort}{2} and the library \file{assoc.pl}. This library is based on discussion in the SWI-Prolog mailinglist, including specifications from Quintus and a library proposal by Richard O'Keefe.\vspace{0.7cm} \begin{description} \predicate[det]{pairs_keys_values}{3}{?Pairs, ?Keys, ?Values} True if \arg{Keys} holds the keys of \arg{Pairs} and \arg{Values} the values. Deterministic if any argument is instantiated to a finite list and the others are either free or finite lists. All three lists are in the same order. \begin{tags} \tag{See also} \predref{pairs_values}{2} and \predref{pairs_keys}{2}. \end{tags} \predicate[det]{pairs_values}{2}{+Pairs, -Values} Remove the keys from a list of Key-Value pairs. Same as \verb$pairs_keys_values(Pairs, _, Values)$ \predicate[det]{pairs_keys}{2}{+Pairs, -Keys} Remove the values from a list of Key-Value pairs. Same as \verb$pairs_keys_values(Pairs, Keys, _)$ \predicate[det]{group_pairs_by_key}{2}{+Pairs, -Joined:list(Key-Values)} Group values with equivalent (\predref{\Sequal}{2}) consecutive keys. For example: \begin{code} ?- group_pairs_by_key([a-2, a-1, b-4, a-3], X). X = [a-[2,1], b-[4], a-[3]] \end{code} Sorting the list of pairs before grouping can be used to group \textit{all} values associated with a key. For example, finding all values associated with the largest key: \begin{code} ?- sort(1, @>=, [a-1, b-2, c-3, a-4, a-5, c-6], Ps), group_pairs_by_key(Ps, [K-Vs|_]). K = c, Vs = [3, 6]. \end{code} In this example, sorting by key only (first argument of \predref{sort}{4} is 1) ensures that the order of the values in the original list of pairs is maintained. \begin{arguments} \arg{Pairs} & \arg{Key}-Value list \\ \arg{Joined} & List of \arg{Key}-Group, where Group is the list of \arg{Values} associated with equivalent consecutive Keys in the same order as they appear in \arg{Pairs}. \\ \end{arguments} \predicate[det]{transpose_pairs}{2}{+Pairs, -Transposed} Swap Key-Value to Value-Key. The resulting list is sorted using \predref{keysort}{2} on the new key. \predicate{map_list_to_pairs}{3}{:Function, +List, -Keyed} Create a Key-Value list by mapping each element of \arg{List}. For example, if we have a list of lists we can create a list of Length-\arg{List} using \begin{code} map_list_to_pairs(length, ListOfLists, Pairs), \end{code} \end{description}