From 99619b710907362518485c14565bfcb3dea65b25 Mon Sep 17 00:00:00 2001 From: rnhmjoj Date: Sun, 27 Nov 2016 20:15:33 +0100 Subject: [PATCH] add permutations --- src/Data/Vec.hs | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/Data/Vec.hs b/src/Data/Vec.hs index 0d4b28b..07b4937 100644 --- a/src/Data/Vec.hs +++ b/src/Data/Vec.hs @@ -179,6 +179,20 @@ transpose (xs :- xss) = gcastWith proof (zipWith (:-) xs (transpose xss)) where proof = min_self (sLength xs) +-- | The 'permutations' function returns the vector of all permutations of the argument. +-- +-- > permutations "abc" ≡ ["abc","bac","cba","bca","cab","acb"] +permutations ∷ Vec a n → Vec (Vec a n) (Fact n) +permutations Nil = Nil:-Nil +permutations (x:-Nil) = (x:-Nil):-Nil +permutations xs@(_:-_) = concatMap (\(y,ys) → map (y:-) (permutations ys)) (select xs) + where + select ∷ Vec a n → Vec (a, Vec a (Pred n)) n + select Nil = Nil + select (x:-Nil) = (x, Nil) :- Nil + select (x:-xs@(_:-_)) = (x,xs) :- map (\(y,ys) → (y, x:-ys)) (select xs) + + -- | 'foldl' applied to a binary operator, a starting value -- and a 'Vec' reduces the vector to a single value obtained -- by sequentially applying the operation from the left to the right.