使用foldl / map查找排列?

时间:2012-12-14 04:57:32

标签: map functional-programming scheme fold

教授向我们展示了一种找出列表的所有排列的抽出方法,即(a b c)=> ((a b c)(a c b)(b a c)(b c a)(c b a)(c a b)),但她说用折叠或地图可以更有效地完成。

功能性思维方式全新。我无法想象我的生活。

2 个答案:

答案 0 :(得分:1)

http://rosettacode.org/wiki/Permutations#Scheme上有一些方案版本(您在此页面上也支持“foldl”,因此还有haskell版本):

(define (insert l n e)
  (if (= 0 n)
      (cons e l)
      (cons (car l) 
            (insert (cdr l) (- n 1) e))))

(define (seq start end)
  (if (= start end)
      (list end)
      (cons start (seq (+ start 1) end))))

(define (permute l)
  (if (null? l)
      '(())
      (apply append (map (lambda (p)
                           (map (lambda (n)
                                  (insert p n (car l)))
                            (seq 0 (length p))))
                     (permute (cdr l))))))

答案 1 :(得分:1)

这个怎么样?

#lang racket    
(define l '(apple banana cheese desk))
(remove-duplicates (for/list ([i 1000000]) (shuffle l)))

当然,你需要增加长列表的常量....

(#nothelpfulsorry)

相关问题