四則演算しかできないeval
30分プログラム、その669。四則演算しかできないevalを作ってみました。
今日、輪講資料を作るためにSICPを読んでました。かの有名な"超言語抽象"の章です。
で、そこを読んでたら、evalを書きたくなったので書いてみました。
ちゃんとLispを実行できるevalは大変なので、四則演算しかできないevalにしてみました。サンドボックス的な使い方をすると便利だったりするかもしれません。
使い方
gosh> (restrict-eval '(* (+ 1 2) 3)) 9 gosh> (restrict-eval '(** 2 4)) 16
ソースコード
#! /opt/local/bin/gosh ;; -*- mode:scheme; coding:utf-8 -*- ;; ;; eval.scm - ;; ;; Copyright(C) 2009 by mzp ;; Author: MIZUNO Hiroki / mzpppp at gmail dot com ;; http://howdyworld.org ;; ;; Timestamp: 2009/09/30 21:47:33 ;; ;; This program is free software; you can redistribute it and/or ;; modify it under MIT Lincence. ;; (use util.match) (define (restrict-eval s) (match s [('+ . xs) (apply + (map restrict-eval xs))] [('- . xs) (apply - (map restrict-eval xs))] [('* . xs) (apply * (map restrict-eval xs))] [('/ . xs) (apply / (map restrict-eval xs))] [('** x y) (expt x y)] [(? number? x) x]))