Scheme编程作业求助:diginlist函数实现不符合预期
Let's fix your diginlist function step by step. First, we'll address syntax errors in your existing code and then integrate removelast and last correctly to meet your requirement.
First: Fix the removelast Syntax Error
Your removelast function has a critical syntax mistake in the recursive call—you're missing parentheses around the function invocation. Here's the corrected version:
(define (removelast L) (if (null? (cdr L)) '() (cons (car L) (removelast (cdr L)))))
Your last function is already correct, so we'll keep it as-is:
(define (last L) (if (null? (cdr L)) (car L) (last (cdr L))))
Understanding the Target Pattern
The goal is to transform lists like '(4 5 3 2 8) into (4 (5 (3) 2) 8). The pattern follows these rules:
- Single-element lists get wrapped in parentheses (e.g.,
'(3)→(3)) - Two-element lists stay as-is (e.g.,
'(5 2)→(5 2)) - Longer lists split into three parts: first element, middle sublist (with first/last elements removed), last element. We recursively process the middle sublist and combine all three parts.
Corrected diginlist Function
Here's the implementation that follows this pattern and uses your helper functions:
(define (diginlist L) (cond ;; Handle empty input list ((null? L) '()) ;; Single-element list: wrap the element in parentheses ((null? (cdr L)) (list (car L))) ;; Two-element list: return as a list of both elements ((null? (cddr L)) (list (car L) (last L))) ;; Longer list: split into first, processed middle, and last elements (else (list (car L) (diginlist (removelast (cdr L))) (last L)))))
Test It Out
When you run your example input:
(diginlist '(4 5 3 2 8)) ; Returns (4 (5 (3) 2) 8)
Let's break down the execution for clarity:
(diginlist '(4 5 3 2 8))splits into4, the middle sublist(removelast (cdr '(4 5 3 2 8)))→'(5 3 2), and8. It combines these as(list 4 (diginlist '(5 3 2)) 8).(diginlist '(5 3 2))splits into5, middle sublist(removelast (cdr '(5 3 2)))→'(3), and2. Combines to(list 5 (diginlist '(3)) 2).(diginlist '(3))matches the single-element case, returning(list 3)→(3).- Putting it all together gives your desired output.
Your original code had issues with invalid cond branch syntax and failed to split the list into meaningful parts. This version fixes those problems and uses your helper functions to handle list splitting cleanly.
内容的提问来源于stack exchange,提问作者Millyraider

