August 19, 2024
P17 - Split a list into two parts; the length of the first part is given
Do not use any predefined functions.
Example:* (split '(a b c d e f g h i k) 3)( (A B C) (D E F G H I K))
lisp
;;; A function that receives a list and a position and returns ;;;
;;; another lists two lists: the first containing the ;;;
;;; elements up to and including the position indicated, and the ;;;
;;; second containing the remainder.
(defun split (pos list)
(list (split-up-to pos list) (split-after pos list))
)
;;; never taking the first part of the LIST, up to' POS
;;; Number of positions starts from 1
;;
;;; Extreme cases:
;;; if POS <= 0, returns empty list
;;; if POS > list length, returns the entire list
(defun split-up-to (pos list)
(cond
((<= pos 0) ())
((null list) list)
(t (cons (car list) (split-up-to (cdr list) (1-pos)))
)
)
;;; A function that receives a list and a position and returns ;;;
;;; another list containing the elements after position ;;;
;;; indicated (positions numbered from 1) ;;
;;
;;; Extreme cases:
;;; if POS <= 0, returns the entire list
;;; if POS > list length, returns empty list
(defun split-after (pos list)
(cond
((<= pos 0) list)
((null list) ())
(t (split-after (cdr list) (1-pos))
)
)