본문 바로가기

기타언어

[LISP] 사용자 정의함수

※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※

따로 LISP 컴파일러나 실행기를 다운받기 싫어서 online에서 진행

 

오른쪽상단의

[get started] -> [try lisp online] 을 눌러서 해당 command line에서 진행

 

https://common-lisp.net/

 

Welcome to Common-Lisp.net!

  Get started Welcome to Common-Lisp.net Introduction Welcome to the amazing world of Common Lisp, the programmable programming language. This site is one among many gateways to Common Lisp. Its goal is to provide the Common Lisp community with developme

common-lisp.net

 

다른사이트들은 print를 해야지 결과값을 출력해주는데 해당사이트에서는 실행결과를 바로보여줌

※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※※

 

 

 

 

LISP 조작함수(기본함수)로 사용자 정의함수 구현하기

 

 

deleteall 함수 정의

 - deleteall 함수는 두 인자 s-expressionlist를 받아서, 리스트 list 안에 있는 모든 s-expression를 제거하는 함수이다.

 - (deleteall ‘b ‘(a b c b))        ->    (a c)

 

union(합집합), intersectioin(교집합), difference(차집합) 함수

   - (union ‘(a b c) ‘(a c d))                  ->     (a b c d)

   - (intersection ‘(a b c) ‘(a c d))          ->     (a c)

   - (difference ‘(a b c) ‘(a c d))            ->     (b)

 

 

(defun deleteall (sexp lis)
(cond ((and (atom sexp) (atom lis) (equal sexp lis) ) nil ) --------------------------1
   ((atom lis) lis)                ---------------------------------------------------2
   ((equal sexp (car lis)) (deleteall sexp (cdr lis)) )    ---------------------------3
   (t (cons (deleteall sexp (car lis)) (deleteall sexp (cdr lis)))) ) )   ------------4

liscarcdr로 분해해 가면서 sexp와 같은 부분을 제외한다. 1번식이나 2번식을 만날 때까지 반복한다.

 

 

 

 

LISP에 자체적으로 정의된 union을 쓰지않고 재호출하는 recursion으로 구현

(defun union (x y)
    (cond ((null x) y)		----------------------------------------------1
          ((member (car x) y) (union (cdr x) y))  ------------------------2
          (t (cons (car x) (union (cdr x) y)) ) ) )  ---------------------3
(defun intersection (x y)
   (cond ((null x) nil)	--------------------------------------------------------1
      ((member (car x) y)  (cons (car x) (intersection (cdr x) y)) )  ---------2
          (t (intersection (cdr x) y) ) ) )	-----------------------------------3
(defun difference (x y)
  (cond ((null x) nil) 		------------------------------------------1
        ((member (car x) y) (difference (cdr x) y))    ---------------------------2
        (t (cons (car x) (difference (cdr x) y))) ) ) )     --------------------------3

 

 

'기타언어' 카테고리의 다른 글

[LISP] LISt Process language  (0) 2022.05.05