分数計算

こんばんは、水野です。趣味は再発明です。

30分プログラム、その142。分数計算を再発明してみる。

いくつかの関数名とすべての機能が標準ライブラリと被ってるけど気にしない。

使い方

gosh> (define half (make-ratio 1 2))
half

gosh> (define one-third (make-ratio 1 3))
one-third

gosh> (add half one-third)
(5 . 6)

gosh> (sub half one-third)
(1 . 6)

gosh> (mul half one-third)
(1 . 6)

gosh> (div half one-third)
(3 . 2)

gosh> (ratio->float half)
0.5

ソースコード

numeratorとdenominatorを何度打ったことか。

#! /opt/local/bin/gosh
;; -*- mode:scheme; coding:utf-8 -*-
;;
;; rational.scm -
;;
;; Copyright(C) 2007 by mzp
;; Author: MIZUNO Hiroki <hiroki1124@gmail.com> 
;; http://mzp.sakura.ne.jp/
;;
;; Timestamp: 2007/09/25 22:08:27
;;
;; This program is free software; you can redistribute it and/or
;; modify it under the same terms as Scheme itself.
;;

(define (gcd n m)
  (if (= m 0)
      n
      (gcd m (modulo n m))))

(define (make-ratio p q) 
  (let1 n (gcd p q)
    (cons (/ p n) (/ q n))))

(define numerator car)
(define denominator cdr)

(define (add p q)
  (make-ratio (+ (* (numerator p) (denominator q))
		 (* (numerator q) (denominator p)))
	      (* (denominator p) (denominator q))))

(define (mul p q)
  (make-ratio (* (numerator p) (numerator q))
	      (* (denominator p) (denominator q))))

(define (uminus r)
  (mul r (make-ratio -1 1)))

(define (sub p q)
  (add p (uminus q)))

(define (reverse r)
  (make-ratio (denominator r) (numerator r)))

(define (div p q)
  (mul p (reverse q)))

(define (ratio->float r)
  (exact->inexact (/ (numerator r) (denominator r))))