cnCalc计算器论坛

 找回密码
 注册
搜索
查看: 823|回复: 0

[SHARP图形机] 99行C代码实现的Lisp解释器【PC- G850】--模拟器可用

[复制链接]
发表于 2023-8-24 23:38:08 | 显示全部楼层 |阅读模式
本帖最后由 FreeBlues 于 2023-8-25 02:03 编辑

国外一位玩家用99行C代码为PC- G850写了一个Lisp解释器,简单来说,Lisp使用一种名为中缀表达式的格式,就是把运算符号写在操作数前面。
例如,平常写一个加法: 2 + 3

Lisp的写法就是: (+ 2 3)

这种书写形式可以跟HP计算器常用的RPN(也叫后缀表达式)做一个类比。

因为它直接使用中缀表达式,其实就相当于其它编程语言经过词法分析,语法分析之后输出的抽象语法树AST,所以它的代码最简洁(你直接把编译结果写出来了),所以我觉得这种编程语言最适合用在计算器上,输入简洁明了。


作者的真机运行截图:

模拟器运行截图:







[HPMuseum论坛原帖](https://www.hpmuseum.org/forum/thread-18559.html)
[TinyLisp项目repo](https://github.com/Robert-van-Engelen/tinylisp)

因为我之前帖子发的那个模拟器没有提供导入代码时自动增加行号的选项,直接导入作者项目代码时会出现错误,所以我这里为850用到的两个c文件加了行号,以确保在模拟器上能正确导入。用于G850真机的通信软件一般都有一个是否增加行号的选项。

这个850Lisp有两个版本,一个是99行的基础版本,另一个是120行的优化版本

99行基础版本:


120行优化版本:



安装方法很简单,任选一个导入模拟器,在 TEXT EDITOR 中把它转换为 BASIC,然后进入 RUN MODE,输入 >RUN 执行


这个版本 Lisp 原语(就是它最基本的东西):
   (eval x)            return evaluated x (such as when x was quoted)
   (quote x)           special form, returns x unevaluated "as is"
   (cons x y)          construct pair (x . y)
   (car p)             car of pair p
   (cdr p)             cdr of pair p
   (add n1 n2 ... nk)  sum of n1 to nk
   (sub n1 n2 ... nk)  n1 minus sum of n2 to nk
   (mul n1 n2 ... nk)  product of n1 to nk
   (div n1 n2 ... nk)  n1 divided by the product of n2 to nk
   (int n)             integer part of n
   (< n1 n2)           #t if n1<n2, otherwise ()
   (eq? x y)           #t if x equals y, otherwise ()
   (not x)             #t if x is (), otherwise ()
   (or x1 x2 ... xk)   first x that is not (), otherwise ()
   (and x1 x2 ... xk)  last x if all x are not (), otherwise ()
   (cond (x1 y1)
         (x2 y2)
         ...
         (xk yk))      the first yi for which xi evaluates to non-()
   (if x y z)          if x is non-() then y else z
   (let* (v1 x1)
         (v2 x2)
         ...
         y)            sequentially binds each variable v1 to xi to evaluate y
   (lambda v x)        construct a closure
   (define v x)        define a named value globally


有了这个Lisp,你就可以用它来定义编写各种函数,下面是作者提供的一些数学函数的编写:

(define abs
    (lambda (n)
        (if (< n 0)
            (- 0 n)
            n)))

(define frac (lambda (n) (- n (int n))))

(define truncate int)

(define floor
    (lambda (n)
        (int
            (if (< n 0)
                (- n 1)
                n))))

(define ceiling (lambda (n) (- 0 (floor (- 0 n)))))

(define round (lambda (n) (+ (floor n) 0.5)))

(define mod (lambda (n m) (- n (* m (int (/ n m))))))

(define gcd
    (lambda (n m)
        (if (eq? m 0)
            n
            (gcd m (mod n m)))))

(define lcm (lambda (n m) (/ (* n m) (gcd n m))))

(define even? (lambda (n) (eq? (mod n 2) 0)))

(define odd? (lambda (n) (eq? (mod n 2) 1)))








本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?注册

x
您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|手机版|cnCalc计算器论坛

GMT+8, 2024-4-29 15:39 , Processed in 0.056413 second(s), 19 queries .

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表