Andy
Andy

Reputation: 3170

Operating on Nested Lists

I have a nested list structure of arbitrary length, with a depth of three. The first level has arbitrary length, as does the second level, but the third level is guaranteed to have a uniform length across the whole thing. An example of said structure would be '(((A B) (C D)) ((E F) (G H)) ((I J))).

I'm trying to write a function that would apply another function across the different levels of the structure (sorry, I don't really know how to phrase that). An example of the function mapping across the example structure would be in this order:

f A C = AC, f B D = BD, f E G = EG, f F H = FH, f I = I, f J = J,

yielding

'((AC BD) (EG FH) (I J))

but imagining that the third level of the list contains many more elements (say, around 32,000 in the final version).

Essentially, what I'm trying to do would be expressed in Haskell as something like f . transpose. I know I need something like (map car (map flatten (car ...))) to get the first part of the first section, but after that, I'm really lost with the logic here. I'm sorry if this is a really convoluted, poorly explained question. I'm just really lost.

How would I go about applying the function across the structure in this manner?

Upvotes: 0

Views: 2511

Answers (2)

Eli Barzilay
Eli Barzilay

Reputation: 29556

It would be much easier to define your f as a function that takes in a list of values. If not, then the last form is easy to add apply to, but it doesn't make it better. (Using a rest argument means that the language will have to create these lists anyway.)

#lang racket
(define data '(((A B) (C D)) ((E F) (G H)) ((I J))))
(define (f xs) (string->symbol (string-append* (map symbol->string xs))))
(map (λ (pairs)
       (list (f (map first pairs))
             (f (map second pairs))))
     data)
(map (λ (pairs) (map f (apply map list pairs)))
     data)
(for/list ([pairs (in-list data)])
  (for/list ([xs (in-list (apply map list pairs))])
    (f xs)))

Upvotes: 1

Dan D.
Dan D.

Reputation: 74655

(define l '(((A B)
   (C D))
  ((E F)
   (G H))
  ((I J)))
)
(define zip (lambda lists (apply map list lists)))
(define (f values) (list 'f values))

(map (lambda (v) (map (lambda values (apply f values)) (apply zip v))) l)

prints

(((f (a c)) (f (b d))) ((f (e g)) (f (f h))) ((f (i)) (f (j))))

Upvotes: 1

Related Questions