comp.lang.scheme で簡単なリスト操作のお題が出ておるな。 http://goo.gl/5GAmということで、やってみました。Scheme(Gauche)です。
以下コード。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; http://twitter.com/baal5084/status/25592330085 | |
;; ((0 a b) (1 c d) (2 e f) (3 g h) (1 i j)(2 k l) (4 m n) (2 o p) (4 q r) (5 s t)) | |
;; -> | |
;; ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t)) | |
(define data | |
'((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) | |
(2 k l) (4 m n) (2 o p) (4 q r) (5 s t))) | |
(use srfi-1) | |
;; (slice-if '(1 1 1 2 2 2 3 4 4 5 5 5 5 5)) | |
;; -> ((1 1 1) (2 2 2) (3) (4 4) (5 5 5 5 5)) | |
(define (slice-if ls . args) | |
(let-optionals* args ((eq? eq?)(combiner cons)) | |
(let rec ((ls ls)(acc '())) | |
(if (null? ls) | |
(reverse acc) | |
(receive (took rest)(span (lambda (e) | |
(eq? e (car ls))) ls) | |
(rec rest (combiner took acc))))))) | |
(define (key-sorted-combine table) | |
(slice-if (sort table (lambda (e1 e2) | |
(< (car e1)(car e2)))) | |
(lambda (e rest) | |
(= (car e)(car rest))) | |
(lambda (took acc) | |
(cons (apply append (map cdr took)) acc)))) | |
(key-sorted-combine data) | |
;; ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t)) |
追記
教えて頂きました!いつもありがとうございます!@valvallow (use gauche.sequence)(use srfi-1)(define(key-sorted-combine lst)(map(pa$ append-map cdr)(group-collection lst :key car)))
(use gauche.sequence) (use srfi-1) (define (key-sorted-combine lst) (map (pa$ append-map cdr) (group-collection lst :key car))) (define data '((0 a b) (1 c d) (2 e f) (3 g h) (1 i j) (2 k l) (4 m n) (2 o p) (4 q r) (5 s t))) (key-sorted-combine data) ;; ((a b) (c d i j) (e f k l o p) (g h) (m n q r) (s t))group-collection 要チェックや!
そういえば、以前 group-sequence は見た記憶が。。
0 件のコメント:
コメントを投稿