Racket Lang - Scheme如何组合环境的变量和值列表

问题描述 投票:1回答:2

我是一个全新的计划,并试图创建一个真正的简单解释器作为起点。

给定两个列表,一个包含以下形式的变量:

(x y z) 

还有第二个包含它们的值:

(1 2 3)

我如何将它们组合起来制作一个如下所示的列表:

((x 1) (y 2) (z 3))

然后我会将其添加到我原来的环境中。我正在努力使用这种类型的编程语言来熟悉这些简单的操作。谢谢。

list lambda scheme racket interpreter
2个回答
2
投票

使用map

(map list '(x y z) '(1 2 3))

2
投票

我目前是一名大学生,使用Dr。Dr.的Begining Student环境。因此,在符号和语法方面可能存在一些差异。

(define (combine-list list1 list2)
  (cond
;; Using (cond) function to create a recursion
    [(or (empty? list1) (empty? list2)) empty]
;; The base case: when to stop the recursion
;; It would be written in the first line cuz it will be evaluated first
    [else (cons (list (first list1) (first list2))
;; The recursive case: construct one typical element of the resulting list
                (combine-list (rest list1) (rest list2)))]))
;; Do the recursive case on all of the rest of the lists

我还没有学到(map)的作用,但在我看来,如果输入是两个参数,函数(combine-list)与(map)具有相同的行为,就像@soegaard在答案中所做的那样。

© www.soinside.com 2019 - 2024. All rights reserved.