Anton Harniakou
Anton Harniakou

Reputation: 880

How do you reverse a sequence in 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))

Upvotes: 3

Views: 914

Answers (2)

wickstopher
wickstopher

Reputation: 999

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.

Upvotes: 3

soegaard
soegaard

Reputation: 31145

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)))

Upvotes: 4

Related Questions