読者です 読者をやめる 読者になる 読者になる

Let's write β

趣味で書いたこととか、RustとLispが好き

二分探索木

Lisp
(defun kv (key val)
  (cons key val))

(defun tree (val left right)
  (list val left right))

(defun tree->val (tree)
  (car tree))

(defun tree->left (tree)
  (cadr tree))

(defun tree->right (tree)
  (caddr tree))

(defun leafp (tree)
  (and (null (tree->left tree))
       (null (tree->right tree))))

(defun walk (tree)
  (cond ((null tree) nil)
        ((leafp tree)
         (format t "Visit: ~A~%" (tree->val tree)))
        (t
         (progn
           (walk (tree->left tree))
           (format t "Visit: ~A~%" (tree->val tree))
           (walk (tree->right tree))))))

(defun tree-search (val tree)
  (cond 
    ((null tree) nil)
    ((= val (tree->val tree))
     tree)
    (t
     (if (< val (tree->val tree))
       (tree-search val (tree->left tree))
       (tree-search val (tree->right tree))))))

(defun %tree-search (val tree)
  (let ((search nil))
    (loop while (not (null tree))
          do
          (if (= val (tree->val tree))
            (progn
              (setf search tree)
              (setf tree nil))
            (if (< val (tree->val tree))
              (setf tree (tree->left tree))
              (setf tree (tree->right tree)))))
    search))

僕が働いているAzit.incでは一緒に働けるエンジニアを募集しています!
採用情報 — 株式会社アジット|Azit Inc.