Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you reverse a sequence in Racket?

Tags:

scheme

racket

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))
like image 812
Anton Harniakou Avatar asked Feb 01 '26 16:02

Anton Harniakou


2 Answers

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)))
like image 98
soegaard Avatar answered Feb 04 '26 05:02

soegaard


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.

like image 31
wickstopher Avatar answered Feb 04 '26 05:02

wickstopher



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!