如何将cons插入lisp上的列表?
我不知道如何返回函数的返回值/ Q2关于上层代码, 例如,我有一个列表,K=1.205ab 我想加一个3.H。 因此,K=1.203.H5 A B 查看我的代码, ***-SYSTEM::%EXPAND-FORM:>carr CAR L应该是lambda表达式 这是什么,我搜索了stackflow,但没有解决错误 ***口齿不清有很多困难。如何将cons插入lisp上的列表?,lisp,Lisp,我不知道如何返回函数的返回值/ Q2关于上层代码, 例如,我有一个列表,K=1.205ab 我想加一个3.H。 因此,K=1.203.H5 A B 查看我的代码, ***-SYSTEM::%EXPAND-FORM:>carr CAR L应该是lambda表达式 这是什么,我搜索了stackflow,但没有解决错误 ***口齿不清有很多困难。 我研究了C、C++汇编和Ruby和I语言。但是,由于Lisp,我感到非常困惑。在Lisp中,您只需键入表达式即可获得返回值。把函数想象成用帕伦斯解方程 对于
我研究了C、C++汇编和Ruby和I语言。但是,由于Lisp,我感到非常困惑。在Lisp中,您只需键入表达式即可获得返回值。把函数想象成用帕伦斯解方程 对于2+3/5,您需要先解2+3,然后再除以5得到结果,对于lisp表达式也是如此2 3 5是相同的表达式,计算结果为1。把它看作是一个方程的简化,直到它被解出来。e、 g:
1 (setq R (cons 1 20))
2 (setq L (cons 5 '(a b)))
3 (setq U (cons 10 'h))
4
5
6 (defun insertcell(R L)
7 (setq x (list r l))
8 (cond ((< (car R) (car L))
9 (setq x (list R L))
10 (print x)
11 (print (car(car(cdr x))))
12 ((> (car R) (car L)
13 (insertcell R (car(cdr x)))))
14 ))
15
16
17 (print r)
18 (print l)
19 (insertcell r l)
20 (insertcell u r)
21
因此,插入函数本身就是:
(/ (+ 2 3) 5) ;
(/ 5 5) ; since `2 + 3` is `5` we replace `(+ 2 3)` with `5`
=> 1 ; "return" value/result of expression
我们遍历列表并递减n,直到它等于0。然后我们使用cons将项目添加到列表中
在C中,遍历将如下所示:
(define (insert pos item xs)
(cond ((null? xs) (cons item '())) ; create a list if passed null else
((= pos 0) (cons item xs)) ; if (n = 0) insert `item' else next
(cons (car xs) (insert (- pos 1) item (cdr xs)))))
其中,结构列表为:
lambda只是没有名称的函数,您可以像传递数据一样传递它们。它们类似于C中的函数指针,您可以在其中编写高阶函数,如mapvoid*fvoid*、struct*list;这将适用于名单上的每个成员
在Lisp中:
struct List{
void *car;
void *cdr;
};
在C中:
其中,若您有一个1..10的列表,并且您编写了map lambda x+1 x xs,您将向列表中的每个成员添加1,从而生成一个数字2..11的列表
注:上述示例使用了Scheme Lisp。您应该看看“计算机程序的结构和解释”SICP,它是对lisp和计算机科学的精彩介绍。insertcell函数中cond的第一个分支缺少一个右括号。应该是:
void map(void (*f)(void*),struct List *list){
if(list==NULL)return;
list->car = f(list->car);
map(f,(struct List*)list->cdr)
}
如果没有适当的缩进和代码格式,您在任何编程语言中都不会走得很远。您可能需要格式化和缩进代码。总是Lisp的好处是:一个好的编辑器可以为您缩进代码。您的代码应该做什么也完全不清楚插入细胞'?什么是3.H?1.20是一个数字。但是3.H???@RainerJoswig修复了这个问题,只需将n与pos交换,pos最初是用n编写的,但为了便于理解,它改为pos
(define (map f xs)
(if (null? xs) ; if empty return empty else apply `f'
'() ; and go to next node
(cons (f (car xs)) (map f (cdr xs)))))
void map(void (*f)(void*),struct List *list){
if(list==NULL)return;
list->car = f(list->car);
map(f,(struct List*)list->cdr)
}
(defun insertcell (R L)
(setq x (list r l))
(cond ((< (car R) (car L))
(setq x (list R L))
(print x)
(print (car (car (cdr x))))) ; <- add a closing paren on this line
((> (car R) (car L)) ; <- add a closing paren here too
(insertcell R (car (cdr x))))))