Chad Brewbaker
Chad Brewbaker

Reputation: 2579

Clean permutation composition in Haskell

What is a clean way to compose two permutations given as integer lists in Haskell?

I know A !! i is the infix array access operator like the C++ equivalent A[i], but I am stuck as to how to map it. In C++ you would loop over i letting C[i] = A[B[i]].

Upvotes: 2

Views: 235

Answers (2)

Edward Kmett
Edward Kmett

Reputation: 29962

If you choose instead to store them in Data.Vector or Data.Vector.Unboxed from the vector package, you can use the backpermute combinator directly.

Then what you want is just backpermute a b, and your permutations can be stored unboxed and packed together in memory, reducing your memory footprint as well.

Upvotes: 7

raymonad
raymonad

Reputation: 949

The Haskell equivalent of that loop in C++ would be something like this:

c = map (a !!) b

So you could say

compose = map . (!!)

and write

c = compose a b

But !! is for lists, not arrays, and indexing is not particularly efficient. You may want to consider using a Vector.

Upvotes: 1

Related Questions