Im a noob in Racket, and I am trying to figure out how to print the elements of one list vertically, thus:
(printv '(1 2 3 4))
1
2
3
4
T
I try with if and cond, thus:
(define (delete x lst)
(cond [(member x lst)(append(reverse(rest(member x(reverse lst))))(rest(member x lst)))]
[else "Error"]
))
(define (printv lst)
(cond [(< 0 (length lst)) ((printf "~a ~%" (first lst))(printv (delete (first lst) lst)))]
[else "T"]))
But I got this error in the moment the list becomes empty
application: not a procedure;
expected a procedure that can be applied to arguments
given: #<void>
arguments...:
Help is appreciated
You should use built-in procedures to make your life easier. And why do you want to delete the elements? just iterate over the list. Try this:
(define (printv lst)
(for-each displayln lst)
(displayln "T"))
Just removing the extra parentheses fixes your problem:
(define (printv lst)
(cond [(< 0 (length lst))
(printf "~a ~%" (first lst))
(printv (delete (first lst) lst))]
[else "T"]))
Some hints:
Doing length
at each iteration makes makes your function exponential time. Eg. doubling the list to display squares the time it takes. A beter approach to check if a list is empty is using (empty? lst)
How you get the rest
of the list using delete
is perhaps the most complicated I've seen. Since you know you are removing the first element you can just replace it with (rest lst)
.
Just printing with a linefeed has a function: displayln
All combined:
(define (printv lst)
(cond [(empty? lst) "T"]
[else
(displayln (first lst))
(printv (rest lst))]))
Pure Scheme version:
(define (printv lst)
(cond [(null? lst) "T"]
[else
(display (car lst))
(newline)
(printv (cdr lst))]))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.