(方案)递归函数来计算某些列表的所有可能组合? [英] (Scheme) Recursive function to compute all possible combinations of some lists?

查看:61
本文介绍了(方案)递归函数来计算某些列表的所有可能组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

计算列表的所有可能组合的递归函数的示例是什么?例如,(combine (list 1 2 3) (list 1 2))应该返回'((1 1) (1 2) (2 1) (2 2) (3 1) (3 2)).

What is an example of a recursive function to compute all possible combinations of lists? For example, (combine (list 1 2 3) (list 1 2)) should return '((1 1) (1 2) (2 1) (2 2) (3 1) (3 2)).

推荐答案

这是我的解决方案.要求SRFI 1和26可用.

Here's my solution. Requires SRFIs 1 and 26 to be available.

(define (cartesian-product first . rest)
  (define (iter l result)
    (define (prepend-all x)
      (map (cut cons <> x) l))
    (concatenate (map prepend-all result)))
  (map reverse (fold iter (map list first) rest)))

这篇关于(方案)递归函数来计算某些列表的所有可能组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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