Recursion Part 2

I am currently practicing lisp and recursion using the following site : https://www.informatimago.com/develop/lisp/l99/ .

There 99 problems to be solved. I think I am on number 11.

I almost got discouraged working on problem 9. The problem asks to group a list according to the numbers given. eg. (1 3 4 5 5 4 4 4 5 5) will give ((1) (3) (4) (5 5) (4 4 4) (5 5)). To tell the truth I worked on this whole day today, and I couldn't get the brackets right until I had to look it up. The issue was not understanding how to use (list) function. Key is to use (append) and (list (list 'a 'a)) to make a pairs or list of list.

But on reflection about my solution this afternoon, I didn't like that it was hacky(not elegant). INfact the solutions on the site are also hacky. Using accumalators in my opinions, during recursive calls is a bit inelagant. He is my final solutions after parching out the inelagant parts.

(defun group (l)
(labels
((group-run (element group l)
;(format t "~a ~%" l )
(cond
((null l) (list (cons element group)))
((eq element (car l)) (group-run element (cons element group) (cdr l)))
(t (cons (cons element group) (group-run (car l) '() (cdr l)))))))
(if (null l)
'()
(group-run (car l) '() (cdr l)))))

Comments

Popular posts from this blog

Recursion Part 1

Back to programming competitons

Debugging Part 3