How to improve simple function's functionalness

Discussion of Common Lisp

How to improve simple function's functionalness

Postby defunct » Fri Jan 27, 2012 7:54 pm

Hello,

I am new to Lisp (and functional programming, really), and just finished the below code that works great.
However, I am told that I should "treat setf as if there were a tax on its use". And yet this simple function has it twice.
How would I go about removing them (without turning my optional argument in to a key)? Also, if you see that I'm making some other non-related mistakes, please let me know.

Code: Select all
; by Will Fitzgerald
(defun strcat (&rest strings)
  (apply 'concatenate 'string strings))

; by me
(defun alternate (text &optional tchar)
  "Return the string with every other character replaced"
  (if tchar () (setf tchar "$"))
  (let ((out ""))
    (dotimes (iter (length text) out)
      (setf out (strcat out
        (if (= 1 (mod iter 2)) tchar
          (subseq text iter (+ iter 1))))))))

Thanks
defunct
 
Posts: 2
Joined: Fri Jan 27, 2012 7:39 pm

Re: How to improve simple function's functionalness

Postby nuntius » Fri Jan 27, 2012 10:30 pm

Don't obsess about pure functional programming. It can be useful or absurd depending on the situation.

Here are some possible improvements. Instead of (if tchar () (setf tchar "$")) use (unless tchar (setf tchar "$")), but the standard way of specifying a default value is (defun alternate (text &optional (tchar "$")). The (subseq text iter (+ iter 1)) is equivalent to (string (char text iter)). Instead of repeated strcats, you could (copy-seq text) and then (setf (char out iter) tchar) inside the dotimes.

If you do want to write a purely functional implementation, think about how to split the problem into a base step and recursive steps that decompose the problem. So a string with a single character is unmodified, a string with two characters becomes "a$", and strings with more characters can be split. The recursive calls usually pass subsets of the problem and return the corresponding subsets of the solution; or they pass the remaining problem, partial solution, and return the completed solution.
User avatar
nuntius
 
Posts: 498
Joined: Sat Aug 09, 2008 10:44 am
Location: Burlington, MA

Re: How to improve simple function's functionalness

Postby defunct » Sun Jan 29, 2012 11:43 am

Helpful. Thanks.
defunct
 
Posts: 2
Joined: Fri Jan 27, 2012 7:39 pm


Return to Common Lisp

Who is online

Users browsing this forum: No registered users and 1 guest