I'm learning Racket just for fun. I've got a question. Is there a way to reverse a sequence? A sort of generic function for reversing things like:
(sequence-reverse "Hello")
(sequence-reverse '(1 2 3))
The problem is that some sequences are infinite, for example the one given by (in-integers). For a finite sequence you can use:
(define (sequence-reverse s)
(reverse
(sequence->list s)))
There is no built in function to do what you want. If you're just concerned with strings and lists, try something like this:
(define (sequence-reverse seq)
(cond ((null? seq) seq)
((list? seq) (reverse seq))
((string? seq) (list->string (reverse (string->list seq))))
(error "Bad sequence")))
You can add other conditions as you see fit - e.g. Vectors offer similar functionality by way of the functions list->vector and vector->list. You probably don't want blanket functionality for all sequences, though. It doesn't really make sense to reverse a hash table or a dictionary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With