# 2.2.3 入れ子になった写像の順列からなる配列をPythonでやってみた...けどできなかった(´･ω･`)...と思ったらできた(・∀・)

SICP2.2.3 Hierarchical Structures の Nested Mappings（入れ子になった写像）の the sequence of permutations of S - x（S-xの順列からなる配列）を Python でやってみた...けどきなかった(´･ω･`)
...と思ったらできた(・∀・)

##### scheme

```;Code used in Sequence Operations
(define (filter predicate sequence)
(cond ((null? sequence)
())
((predicate (car sequence))
(cons (car sequence)
(filter predicate (cdr sequence))))
(else (filter predicate (cdr sequence)))))
(define (accumulate op initial sequence)
(if (null? sequence)
initial
(op (car sequence)
(accumulate op initial (cdr sequence)))))
;end

(define (flatmap proc seq)
(accumulate append () (map proc seq)))

(define (permutations s)
(if (null? s)                    ; empty set?
(list ())                   ; sequence containing empty set
(flatmap (lambda (x)
(map (lambda (p) (cons x p))
(permutations (remove x s))))
s)))

(define (remove item sequence)
(filter (lambda (x) (not (= x item)))
sequence))

(permutations (list 1 2 3))
; ((1 2 3) (1 3 2) (2 1 3) (2 3 1) (3 1 2) (3 2 1))
```
##### python

（よく見たらSICPに『sequence containing empty set（空セットを含む配列）』って書いあった）

```#Code used in Sequence Operations
def filter(prodicate, sequence):
if not sequence:
return []
if prodicate(sequence[0]):
return [sequence[0]] + filter(prodicate, sequence[1:])
return filter(prodicate, sequence[1:])
def accumulate(op, initial, sequence):
if not sequence:
return initial
return op(sequence[0], accumulate(op, initial, sequence[1:]))
#end

def flatmap(proc, seq):
return accumulate(lambda x,s:x + s, [], map(proc, seq))

def permutations(s):
if not s:
return [[]]
return flatmap(lambda x:
map(lambda p:[x] + p,
permutations(remove(x, s))),
s)
def remove(item, sequence):
return filter(lambda x:not x == item,
sequence)

print permutations([1,2,3])
```

`[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]`

うまくいかなかった(||ﾟДﾟ)

うまくいった！よかった(・∀・)