尝试实现一种对树进行平方的方法会在关键字后给出错误 4 部分

Trying to implement a method to square a tree gives error 4 parts after keyword

我正在尝试实现一种方法,该方法能够使用 map 对可以由子列表(树)组成的列表进行平方。

这意味着 (square-tree-map (list 1 3 (list 3 4))) 应该 return (1 9 (9 16)).

我想出了这个代码:

(define (square-tree-map tree)
  (define (sq x) (* x x))
  (map (lambda (t) 
         (if (pair? t) 
             (cons (square-tree-map (car t))
                   (square-tree-map (cdr t)))
             sq t)) 
       tree))

这给出了错误:

if: bad syntax; has 4 parts after keyword in: (if (pair? t) (cons (square-tree-mapped (car t)) (square-tree-mapped (cdr t))) sq t)

我在 if 运算符后只看到两种可能性,而不是 4。为什么会出现此错误?

原来是语法错误:

(if (pair? t) 
     (cons (square-tree-map (car t))
           (square-tree-map (cdr t)))
     sq t)) 

应该是:

(if (pair? t) 
    (cons (square-tree-map (car t))
           (square-tree-map (cdr t)))
     (sq t))) 

所以错误是因为 sqt 算作两个。

通过执行上述操作,我看到应该围绕它构建另一个 if-check 以确保我们不会尝试映射不可能的单个值:

(define (square-tree-map tree)
  (define (sq x) (* x x))
  (if (pair? tree)
      (map (lambda (t) 
             (if (pair? t) 
                 (cons (square-tree-map (car t)) 
                       (square-tree-map (cdr t)))
                 (sq t)))
           tree)
      (sq tree)))

(square-tree-map (list 1 (list 4 2) 3 5))
;; => (1 (16 4) 9 25)

最后 cons a car 和 cdr 是多余的操作,因为 l = (cons (car l) (cdr l)) 根据定义。较短的解决方案是:

(define (square-tree-map tree)
  (define (sq x) (* x x))
  (map (lambda (t) 
         (if (pair? t) 
             (square-tree-map t)
             (sq t)))
       tree))

感谢您的关注。