728x90
<여러 재귀함수들 구현>
🥝 홀수찾는 함수(anyoddp)
(defun anyoddp (x)
(cond ((null x) nil) //x가 null이라면 nil 출력
((oddp (first x)) t) //x의 첫번째 원소가 홀수라면 출력
(t (anyoddp (rest x))))) //둘다 아니라면 rest x가 재귀로 들어감
🥝 팩토리얼 함수(factorial)
(defun fact (n)
(cond ((zerop n) 1)
(t (* n (fact (- n 1))))))
🥝 리스트 원소개수(count-slices)
(defun count-slices (loaf)
(cond ((null loaf) 0)
(t (+ 1 (count-slices (rest loaf))))))
🥝 첫번째 원자 찾는 함수(find-first-atom)
* atom은 원자(=나눌 수 없는 ex 단어)인 경우 true를 반환, 아니면 nil
(defun find-first-atom (x)
(cond ((atom x) x)
(t (find-first-atom (first x)))))
🥝 n만큼 ha가 추가되는 함수(laugh)
(defun laugh (n)
(cond ((zerop n) nil)
(t (cons 'ha (laugh (- n 1))))))
🥝 nth n번째 원소 추출
(defun my-nth (n x)
(cond ((zerop n) (first x)) //n이 0면 첫번째 원소 출력
(t (my-nth (- n 1) (rest x))))) //아니면 n-1, rest x를 인풋으로 넣음
🥝 symbol을 추출(extract-symbols)
(defun extract-symbols (x)
(cond ((null x) nil) //기저조건, x가 null이면 nil 출력
((symbolp (first x))
(cons (first x) (extract-symbols (rest x)))) //sympbol이면 cons하여 만든다.
(t (extract-symbols (rest x))))) //symbol이 아니면 묶지 않고 넘어간다.
🥝 숫자 찾는 함수
(defun find-number (x)
(cond ((numberp x) x) //x가 단일원소로 숫자이면 그 원소 출력
((atom x) nil)
;; x가 리스트일 때
(t (or (find-number (car x))
(find-number (cdr x))))))
🥝 my-mapcar 함수
*mapcar : 여러개 인풋을 받아서 그 인풋별 함수의 결과값을 리스트로 출력
(defun my-mapcar (fn x) //fn:적용할 함수 x:리스트로 된 인풋값
(cond ((null x) nil)
(t (cons (funcall fn (first x))
(my-mapcar fn (rest x))))))
교재에 있는 함수들입니다~~
728x90
'Major > Lisp' 카테고리의 다른 글
[Lisp] Chapter 10 Assignment (0) | 2021.06.09 |
---|---|
[Lisp] Ch 9 - Input/Output (0) | 2021.06.01 |
[Lisp] Ch 7 Applicative Programming(실용적인 프로그래밍) (0) | 2021.05.29 |
[Lisp] Ch 6 - 리스트 자료구조 (List Data Structures) (0) | 2021.04.21 |
[Lisp] Ch 11 - 반복문과 블록구조 (Iteration and Block Structure) (0) | 2021.04.15 |