In: Computer Science
Write a function in lisp XIT that counts the number of items in each sub-list of a list and returns the count in a list. It should only work if there are two levels of brackets in the parameter (simple lists inside the parent list). Thus:
(XIT '((A B C))) |
-> (3) |
(XIT '((A) (A B) (A B C))) |
-> (1 2 3) |
(XIT '((1 2))) |
-> (2) |
(XIT '(1 (2 3))) |
-> '(ILLEGAL) |
(XIT '((1 2 (3)))) |
-> '(ILLEGAL) |
Answer: The below code does the required task.
Here a helper function '(check (lst))' is used. This function takes in a list as a parameter and returns 'T' if all the elements of if are not lists. Else it returns 'nil'.
Code:
check function:-
(defun check (lst)
(setq len2 (length lst))
(setq j 0)
(loop
(setq tmp2 (nth
j lst))
(if (listp
tmp2)
(return nil)
)
(setq j (+ j
1))
(when (= j
len2)
(return t)
)
)
)
XIT function:-
(defun XIT (a)
(if (not (listp a))
(progn (return
''(illegal)))
(progn
(setq len (length a))
(setq i 0)
(setq ret '())
(loop
(setq tmp (nth i a))
(if (not (listp tmp))
(progn
(return ''(illegal)))
(if (not
(check tmp))
(progn (return ''(illegal)))
(progn
(setq l (length tmp))
(setq ret (append ret (list
(eval l))))
(setq i (+ i 1))
(when (= i len) (return
ret))
)
)
)
)
)
)
)
Screenshots: