知道如何在 dr racket 中交错两个列表吗? [英] Any idea of how to interleave two lists in dr racket?

查看:41
本文介绍了知道如何在 dr racket 中交错两个列表吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是当列表的长度不同时,知道怎么做吗?

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

我必须使用 map 之类的函数

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. Thank you.

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

如果列表的长度不同,这就是我得到的:

if lists have different length this is what I get:

map:所有列表的大小必须相同;参数是:# '(1 2 3 4 5) '(a b c)

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

我想得到 (1 a 2 b 3 c 4 5)

I'm trying to get (1 a 2 b 3 c 4 5)

推荐答案

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

这篇关于知道如何在 dr racket 中交错两个列表吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆