This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

How to improve simple function's functionalness

3 posts · 2051 views

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.
; 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

Re: How to improve simple function's functionalness

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.

Re: How to improve simple function's functionalness

Helpful. Thanks.