Kaz Kylheku
5/27/2016 10:55:00 PM
On 2016-05-27, WJ <w_a_x_man@yahoo.com> wrote:
> WJ wrote:
>
>> Kenny Tilton wrote:
>>
>> > (defun p2b (pairs &key ((:test test) #'eql))
>> > "((A 1) (A 2) (B 2) (C 2) (C 3)) ==> ((A 1 2) (B 2) (C 2 3))"
>> > (loop with bunch = nil
>> > for (one two) in pairs
>> > do (push two (cdr (or (assoc one bunch :test test)
>> > (car (push (list one) bunch)))))
>> > finally (return bunch)))
>>
>> Gauche Scheme:
>>
>> (define (p2b pairs)
>> (let1 h (make-hash-table)
>> (for-each (cut apply hash-table-push! h <>) pairs)
>> (hash-table->alist h)))
>>
>> (p2b '((A 1) (A 2) (B 2) (C 2) (C 3)))
>> ===>
>> ((A 2 1) (B 2) (C 3 2))
>
> OCaml:
>
> open List ;;
>
> let p2b pairs =
> let h = Hashtbl.create 99 in
> iter
> (fun (k,v) -> Hashtbl.add h k v)
> pairs ;
> map
> (fun k -> k, Hashtbl.find_all h k)
> (sort_uniq compare (map fst pairs)) ;;
>
> p2b ["A",1; "A",2; "B",2; "C",2; "C",3] ;;
> ===>
> [("A", [2; 1]); ("B", [2]); ("C", [3; 2])]
That's not even the correct output. "A" looks like a string
and it's not on the same level of nesting as 2 and 1.
This is the TXR Lisp interactive listener of TXR 141.
Use the :quit command or type Ctrl-D on empty line to exit.
1> (hash-alist
(hash-update [group-by first '((A 1) (A 2) (B 2) (C 2) (C 3))]
(op mapcar second)))
((C 2 3) (B 2) (A 1 2))
How about:
2> (mapcar [juxt caar (op mapcar cadr)]
[partition-by car '((A 1) (A 2) (B 2) (C 2) (C 3))])
((A (1 2)) (B (2)) (C (2 3)))
Close, and more so than the OCaml. callf should help us here:
3> (mapcar [callf cons caar (op mapcar cadr)]
[partition-by car '((A 1) (A 2) (B 2) (C 2) (C 3))])
((A 1 2) (B 2) (C 2 3))
Bingo.