Beginner - Function Critique
- From: crystal1 <crystal1@xxxxxxxxxxxx>
- Date: Fri, 30 Sep 2005 08:53:45 -0700
See below. These functions have been created a thousand times and are trivial, but I wrote these instances myself and am a pretty proud beginner. What do you think?
A week ago recursion was still pretty hazy, but a after reading "Common Lisp, An Interactive Approach" the progress has been steady. What a great book.
;;;;;;;;;;;;;;;;
(defpackage :string-utils (:use :common-lisp))
(in-package :string-utils)
(defun line-split (s d)
"Return a list of substrings in string S when delimited by delimiter D."
(check-type s string)
(check-type d character)
(if (= (length s) 0) '()
(cons (getf (line-split1 s d) :string)
(line-split (getf (line-split1 s d) :remainder) d))))(defun line-split1 (s d)
"Helper function for LINE-SPLIT. Return a list with elements of supplied string S up to the first instance of delimiter D as :STRING and the remaining string after the delimiter as :REMAINDER."
(if (position d s) (list :string (subseq s 0 (position d s))
:remainder (subseq s (1+ (position d s))))
(list :string s :remainder "")))
(defun read-file (filename delimiter)
"Return a list of lists containing strings in pathname FILENAME delimited by character DELIMITER."
(let ((output '()))
(with-open-file (in filename)
(do ((line (read-line in nil) (read-line in nil)))
((null line))
(push (line-split line delimiter) output))
(nreverse output))))
(defmacro join-strings (&rest strings) "Return the result of concatenating the supplied strings." `(concatenate 'string ,@strings))
(defun rjust (s w) "Right justify string S by W spaces." (rjust1 s (- w (length s))))
(defun rjust1 (s w)
"Helper function for RJUST."
(if (<= w 0) s
(join-strings (rjust1 s (1- w)) " ")))(defun ljust (s w) "Left justify string S by W spaces." (ljust1 s (- w (length s))))
(defun zfill (s w) "Left justify string S by W 0 characters." (ljust1 s (- w (length s)) "0"))
(defun ljust1 (s w &optional (c " "))
"Helper function for LJUST."
(if (<= w 0) s
(join-strings c (ljust1 s (1- w) c))))
.- Follow-Ups:
- Re: Beginner - Function Critique
- From: Alan Crowe
- Re: Beginner - Function Critique
- From: Kenny Tilton
- Re: Beginner - Function Critique
- From: Pascal Bourguignon
- Re: Beginner - Function Critique
- From: Adrian Kubala
- Re: Beginner - Function Critique
- Prev by Date: Re: C++ and lisp and Games
- Next by Date: Re: C++ and lisp and Games
- Previous by thread: Re: Will Clinger's Types Rant
- Next by thread: Re: Beginner - Function Critique
- Index(es):