Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any idea of how to interleave two lists in Dr Racket?

The problem is when lists have a different length, any idea of how to do it?

I have to use functions like map or something like that.

This is the code I wrote so far, it works with lists of the same length but it also needs to work with lists of different lengths:

(define (interleave list1 list2)
 (flatten 
   [map (lambda (x y) (cons x (cons y null)))
        list1 list2]))

When lists have different length this is the error that I get:

map: all lists must have same size; 
arguments were: #<procedure> '(1 2 3 4 5) '(a b c)

I'm trying to get (1 a 2 b 3 c 4 5) as the result here. Thank you.

like image 688
user3786933 Avatar asked Jan 18 '26 02:01

user3786933


1 Answers

#lang racket

(define (weave xs ys)
  (match (list xs ys)
    [(list (cons x xs) (cons y ys)) (cons x (cons y (weave xs ys)))]
    [(list '() ys)                  ys]
    [(list xs '())                  xs]))
like image 156
soegaard Avatar answered Jan 19 '26 19:01

soegaard



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!