;どう書く?org 分数を小数に展開 をCommonLispで

久しぶりに続き。
どう書く?に出題がどんどんでちゃって、追い付く気配が全くない。
マイペースでやってくか。


今回も処理速度とか無視。
例題は通ったけどバグはあるかも。

;;どう書く?org 分数を小数に展開
(defun calc(x)
  (multiple-value-bind (a b)
      (truncate x)
      (format nil "~A.~A" a (calc_ "" (* 10 (numerator b)) (denominator b) (make-hash-table) 0))))

(defun calc_(str n d dic i)
  (multiple-value-bind (v exists)
      (gethash n dic)
    (if exists
    (concatenate 'string (insert-mark str v "{") "}")
      (multiple-value-bind (a b)
      (floor n d)
    (if (= b 0)
        (concatenate 'string str (princ-to-string a))
      (progn
        (setf (gethash n dic) i)
        (calc_ (concatenate 'string str (princ-to-string a)) (* b 10) d dic (1+ i))))))))
        
(defun insert-mark(n i c)
  (let ((s (princ-to-string n)))
    (concatenate 'string (subseq s 0 i) c (subseq s i))))