Permutations: Difference between revisions

→‎{{header|Haskell}}: Slight reformulation of the Mathematica-based version, in terms of the applicative <*> operator
(→‎{{header|Python}}: with destructive list updates)
(→‎{{header|Haskell}}: Slight reformulation of the Mathematica-based version, in terms of the applicative <*> operator)
Line 2,939:
insertEverywhere x l@(y:ys) = (x:l) : map (y:) (insertEverywhere x ys)</lang>
 
A serialized version: (based on [[#Mathematica|the Mathematica version]]):
{{Trans|Mathematica}}
<lang haskell>
<lang haskell>import qualified Data.List as L
 
ins :: [a] -> [a] -> Int -> [a]
ins list x n = listn ++ [x] ++ listn' where (listn,listn')=L.splitAt n list
ins x list n = L.intercalate [x] $ [snd, fst] <*> [L.splitAt n list]
 
permutations :: [a] -> [[a]]
permutations s =
foldl (\ac x -> ac >>= (fmap . ins x) <*> (enumFromTo 0 . length)) [[]]
 
ac >>= (\l-> (\k->ins l x k) <$> [0..length l]))
main :: IO ()
[[]] s
main = print $ permutations [1, 2, 3]</lang>
</lang>
{{Out}}
<pre>[[1,2,3],[2,3,1],[3,1,2],[2,1,3],[1,3,2],[3,2,1]]</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
9,659

edits