Re: Beginner - Function Critique





crystal1 wrote:
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?

Fun, right? What languages have you used before?


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 "")))

That is a clever way of returning more than one value, but you might be interested in a simpler approach:


   (if (position d s)
       (values (subseq s 0 (position d s))
               (subseq s (1+ (position d s))))
       s)

Then in the caller:

   (multiple-value-bind (segment remainder)
      (line-split1...)
     <do something clever with segment and remainder>)

Note that m-v-b is OK with line-split1 not returning a second value on the last segment, and that I feel nil is a better way in Lisp to denote "there is no remainder". Much easier to test for in client code.

--
Kenny

Why Lisp? http://wiki.alu.org/RtL_Highlight_Film

"I've wrestled with reality for 35 years, Doctor, and I'm happy to state I finally won out over it."
Elwood P. Dowd, "Harvey", 1950


.