Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

Toy Problem of the Week

Name: Anonymous 2009-12-12 18:22

I was raking around on the net and found this problem and coded up a solution. Once we get at least 10 solutions I'll post mine and a link to where I found the problem.
Any language, any libraries (but declare them) allowed. Aim for clarity and conciseness. Assume the input is well formed. Mine is 5 lines of scheme code (6 if we include requiring a library). No calling an "answer" function that "you wrote already and put in an external lib" ;)

Consider the problem of turning a list consisting
of a mix between symbols and non-symbols into a
list of lists of the symbol and its following
non-symbols. That is:

Input:    ({<symbol> <non-symbol>*} ... )
Output:   ((<symbol> (<non-symbol>*)) ...)
Example:     (a 1 2 3 b 4 5 c d 8 9 e)
           -> ((a (1 2 3)) (b (4 5)) (c ()) (d (8 9)) (e ()))

Name: 13 2009-12-12 20:54

Out of boredom, wrote one state-machine-based implementation, only using minimal CL:

(defun frob-flat-list (list) 
  (let ((element (pop list))
        symbol non-symbols result)   
    (tagbody      
     SYMBOL        
       (unless (symbolp element)
         (error "Not a symbol: ~A" element))
       (setf symbol element)
       ;;(go NON-SYMBOL)
     NON-SYMBOL
       (setf element (pop list))
       (cond
         ((symbolp element)            
          (push (list symbol (nreverse non-symbols)) result)
          (setf non-symbols nil)
          (go SYMBOL))
         (t           
          (push element non-symbols)         
          (go NON-SYMBOL))))
    (nreverse result)))

;TOY-PROBLEMS> (frob-flat-list '(a 1 2 3 b 4 5 c d 8 9 e))
;((A (1 2 3)) (B (4 5)) (C NIL) (D (8 9)) (E NIL))

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List