问题描述
我是新手,在使用car和cdr时遇到了困难.我在ast中有一个AST字符串文字.
I am new to scheme and having a hard time with using car and cdr. I have an AST string literal in ast.
(define ast '(program
((assign (var i int) (call (func getint void int) ()))
(assign (var j int) (call (func getint void int) ()))
(while (neq (var i int) (var j int))
((if (gt (var i int) (var j int))
((assign (var i int) (minus (var i int) (var j int))))
((assign (var j int) (minus (var j int) (var i int)))))))
(call (func putint int void) ((var i int)))))
)
我知道汽车返回ast的头.所以
I know car returns the head of ast. So
(car ast)
返回程序".
我很困惑如何使用car和cdr从ast获取字符串,例如"assign","while","if"和"call".
I am confused how to use car and cdr to get strings from ast such as 'assign, 'while, 'if, and 'call.
推荐答案
您需要从球拍参考:
列表是递归定义的:它可以是常量null,或者是其第二个值是列表的一对.
A list is recursively defined: it is either the constant null, or it is a pair whose second value is a list.
基本上每个对(x . y)
由两个元素组成-car
让我们x cdr
让我们y.
Basically every Pair (x . y)
is made of two elements - car
gets us x cdr
gets us y.
请注意,x 和 y既可以成对也可以列出自己,就像您的AST一样,即(出于同一参考):
Notice that x and y can both be pairs or lists themselves, just like your AST, ie(out of same reference):
> (define lst1 (list 1 2 3 4))
>lst1
'(1 2 3 4)
注意'(1 2 3 4)
实际上是:(1 . ( 2 . ( 3 . ( 4 . ())))
<-了解方案中的实现非常重要.
notice that '(1 2 3 4)
is actually: (1 . ( 2 . ( 3 . ( 4 . ())))
<-- Very important to know the implementation in scheme.
> (car lst1)
1
> (cdr lst1)
'(2 3 4)
> (car (cdr lst1))
2
另一种链接汽车和cdr呼叫的方法(从右侧读取):cadr表示(cdr lst)
,然后将car
应用于答案=>. (car (cdr lst))
== (cadr lst)
Another way to chain car and cdr calls(read from the right):cadr means (cdr lst)
and then apply car
on the answer => (car (cdr lst))
== (cadr lst)
> (cdddr lst1)
'(4)
> (cadddr lst1)
4
> (define lst2 (list (list 1 2) (list 3 4)))
>lst2
'((1 2) (3 4))
== ( ( 1 . ( 2 . ()) ) . ( 3 . ( 4 . () )))
> (car lst2)
'(1 2)
>(cdr lst2)
'((3 4))
实际上是((3 . (4 . () ) ) . () )
== ((3 4) . ())
== ((3 4))
which is actually ((3 . (4 . () ) ) . () )
== ((3 4) . ())
== ((3 4))
您没有询问,但我假设您将遍历树/列表.最终,您将必须进行递归遍历(除非使用当前不适合的高级方法,即准备就绪时检查CPS),就像这样:
You did not ask but I'm assuming you are going to traverse through the tree/list.Ultimately you will have to traverse with a recursion (unless using advanced method not suitable at this stage, ie check CPS when ready ) like so:
(define runner
(lambda (tree)
(if (null? tree)
null
(let ((first_element (car tree))
(rest_of_tree (cdr tree)))
;body:
;do some logic like:
;if first is list call runner on it:
;(runner rest_of_tree)
;possibly chain answer of logic and call together
;else check/return string is there (recognize tree root)
))))
希望这有助于欢迎问题.
Hope this helps questions welcome.
这篇关于使用汽车和cdr的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!