Scheme中的笛卡尔积 [英] Cartesian product in Scheme
本文介绍了Scheme中的笛卡尔积的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在尝试做一个返回 n 个集合的笛卡尔积的函数,在 Scheme 博士中,这些集合以列表的形式给出,我一整天都被困在这个问题上,我想要一些从哪里开始的指南.
I've been trying to do a function that returns the Cartesian Product of n sets,in Dr Scheme,the sets are given as a list of lists,I've been stuck at this all day,I would like a few guidelines as where to start.
----后期编辑-----
----LATER EDIT -----
这是我想出的解决方案,我确信它不是迄今为止最有效或最简洁的,但我只学习了 3 周的 Scheme,所以请对我放轻松.
Here is the solution I came up with,I'm sure that it's not by far the most efficent or neat but I'm only studing Scheme for 3 weeks so be easy on me.
推荐答案
;returs a list wich looks like ((nr l[0]) (nr l[1])......)
(define cart-1(λ(l nr)
(if (null? l)
l
(append (list (list nr (car l))) (cart-1 (cdr l) nr)))))
;Cartesian product for 2 lists
(define cart-2(λ(l1 l2)
(if(null? l2)
'()
(append (cart-1 l1 (car l2)) (cart-2 l1 (cdr l2))))))
;flattens a list containg sublists
(define flatten
(λ(from)
(cond [(null? from) from]
[(list? (car from)) (append (flatten (car from)) (flatten (cdr from)))]
[else (cons (car from) (flatten (cdr from)))])})
;applys flatten to every element of l
(define flat
(λ(l)
(if(null? l)
l
(cons (flatten (car l)) (flat (cdr l))))))
;computes Cartesian product for a list of lists by applying cart-2
(define cart
(lambda (liste aux)
(if (null? liste)
aux
(cart (cdr liste) (cart-2 (car liste) aux)))))
(define (cart-n l) (flat (cart (cdr l ) (car l))))
这篇关于Scheme中的笛卡尔积的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文