Date: Fri, 17 Jan 2003 01:40:11 -0800 From: Bakul Shah <bakul@bitblocks.com> To: "Crist J. Clark" <cjc@FreeBSD.ORG> Cc: freebsd-chat@FreeBSD.ORG Subject: Re: Script Challenge Message-ID: <200301170940.EAA14712@dreadnought.cnchost.com> In-Reply-To: Your message of "Thu, 16 Jan 2003 21:44:59 PST." <20030117054458.GA50247@blossom.cjclark.org>
next in thread | previous in thread | raw e-mail | index | archive | help
> Items in the database can contain sub-items which in turn contain > sub-items with no hard limit to the recursion. ... > I want to sort each level. ... > Like I said, I used a Perl script with a recursive function to do > it, but it ain't all that pretty. I suspect I'm missing a really cool > way to do it. Any suggestions? (Any language will do.) Attached below is a small scheme script (using Aubrey Jaffer's scm and slib -- see /usr/ports/lang/scm). When it is fed your sample input :b_item (value) :a_item ( :z_subitem(value) :x_subitem(value) :y_subitem( :r_subsubitem(value) :t_subsubitem(vaule) :s_subsubitem(value) ) :w_subitem(value) ) :c_item(value) It produces ((:a_item (:w_subitem value) (:x_subitem value) (:y_subitem (:r_subsubitem value) (:s_subsubitem value) (:t_subsubitem vaule)) (:z_subitem value)) (:b_item value) (:c_item value)) As you can see the output is formatted as one big list. Such "lispy" formats are trivial to read in and easy to process. But if you don't like that, you can write a simple converter back to your format or convert this script to linenoise perl. Note: the input can have any amount of whitespace and there is virtually no limit on nesting. But the script does assume Scheme input syntax. If not, you have to replace (read) with your own. It also assumes all lists have either 1 item or an even number of items (i.e. no errors). -- bakul cat > sortdb.scm <<EOF #! /usr/local/bin/scm (require 'sort) (require 'pretty-print) (define (less? a b) (string<? (symbol->string (car a)) (symbol->string (car b)))) (define (sort-value l) (if (or (null? l) (null? (cdr l))) l (sort-list l '()))) (define (sort-list l result) (if (null? l) (sort result less?) (sort-list (cddr l) (cons (cons (car l) (sort-value (cadr l))) result)))) (define (read-db p) (let loop ((result '()) (item (read p))) (if (eof-object? item) (sort-value (reverse result)) (loop (cons item result) (read p))))) (pretty-print (read-db (current-input-port))) EOF chmod +x sortdb.scm sortdb.scm < tst-db > sorted-tst-db To Unsubscribe: send mail to majordomo@FreeBSD.org with "unsubscribe freebsd-chat" in the body of the message
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?200301170940.EAA14712>