Problem: give the smallest possible complete subroutine/function/method
definition in a language of your choice which, when called with a list,
array, whatever, returns the power set of that list. It may be in any order,
but must not contain duplicates. e.g.:
p([1, 2, 3]) returns:
[[], [1], [2], [3], [2, 3], [1, 2], [1, 3], [1, 2, 3]]
haskell: 46 (86 bz2)
{- p [1,2,3] -}
p= foldr ( \ h t-> t++ map ( h: ) t) [ [ ] ]
perl: 53 (93 bz2)
# p(1, 2, 3)
sub p{ my $y = pop ; $y ? map { [ $y ,@ $_ ] , $_ } &p : [ ] }
haskell*: 64 (102 bz2)
{- p [0..] -}
p l= [ ] : do { ( n,x) <- zip [ 0 ..] l;map ( x: ) $ take ( 2 ^ n) $ p l}
ruby: 69 (105 bz2)
# r([1, 2, 3])
def r( l) l==[ ] ?[ l] :( a=l.pop ;s=r l;s+ s.map { | i| [ a] + i} ) end
python: 73 (99 bz2)
# p([1, 2, 3])
p= lambda l:l and p( l[ 1 :] ) +[ l[ :1 ] +y for y in p( l[ 1 :] ) ] or [ l]
ocaml: 77 (117 bz2)
(* p [1; 2; 3];; *)
let rec p= function a:: b-> p b@List . map( ( @) [ a] ) ( p b) | l-> [ l]
coffeescript: 85 (117 bz2)
# p [1, 2, 3]
p=( l) -> return [ [ ] ] if ! l.length ; s=p l[ 1 ..] ; s.concat ( [ l[ 0 ] , x...] for x in s)
prolog: 89 (112 bz2)
<% '%' %> p([1,2,3],X).
s([],L).s([A|B],L):-member(A,L),s(B,L).p(L,X):-setof(Z,s(Z,L),X).
lisp: 88 (109 bz2)
; (p '(1 2 3))
( defun p( l ) ( if
l ( mapcan #'( lambda ( x) `( , x( , ( car l ) ., x) ) ) ( p( cdr l ) ) ) `( , l ) ) )
javascript: 152 (158 bz2)
// p([1, 2, 3])
function p( l) { if ( ! l.length ) return [ [ ] ] ; var a= [ ] ; var s= p( l.slice ( 1 ) ) ; for ( var
i= 0 ; i< s.length ; i++ ) a.push ( s[ i] , [ l[ 0 ] ] .concat ( s[ i] ) ) ; return a}
php: 157 (150 bz2)
# p(array(1, 2, 3))
function p( $l ) { if ( ! $l ) return
array ( $l ) ; $a = array ( ) ; foreach ( p( array_slice ( $l , 1 ) ) as $i ) { $a [ ] = $i ; $a [ ] = array_merge ( array ( $l [ 0 ] ) , $i ) ; } return $a ; }
gnu smalltalk: 163 (170 bz2)
"(Set from: #(1 2 3)) p"
Set extend[ p [ |a s |^self isEmpty
ifTrue:[ Set with:self ] ifFalse:[ a := self remove:self anyOne. s := self p.
s +( s collect:[ :i |i+( Set with:a ) ] ) ] ] ]
*: The second haskell entry works for infinite lists!