permutation in haskell
I have a list:
let a = [1, 2, 3]
I need to get another list:
[1, 2, 3] ++ [1*2, 2*3, 1*3] ++ [1*2*3]
It is a product of all pos开发者_如何学Pythonsible unique coombinations of list's elements. I have founded permutations in Data.List, but as I see it is something different.
Is there any library functions to get this list or can you give me examles how can I create your own function.
Thanks.
For a library function, you can use subsequences
from Data.List
:
Prelude Data.List> subsequences [1,2,3]
[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
You can get all of the products using map product $ subsequences [1,2,3]
.
But that is not in the same order as you specified. So you can sort it,
using sortBy
from Data.List
and comparing
from Data.Ord
:
Prelude Data.List Data.Ord> sortBy (comparing length) $ subsequences [1,2,3]
[[],[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3]]
Again, get the products using map product
.
Your other idea, to write a function yourself, is the best idea if you are learning Haskell. Give it a try!
You want all subsequences, not permutations. Permutations give you all possible orders of the same elements. Whereas a subsequence is any sequence that has a subset of elements of the original, in the same order.
In addition to the function mentioned above, there's a clever trick to do this with some other library functions, but I'm not sure how helpful it will be to you.
import Control.Monad (filterM)
subsequences' :: [a] -> [[a]]
subsequences' = filterM $ const [False, True]
This trick takes advantage of the viewpoint of the list monad as modeling non-deterministic calculation. For each element in the list, it's included or not, non-deterministically, regardless of what it is.
It's efficient, and precisely the kind of thing the list monad is designed for, but it's somewhat opaque. You would probably learn more from implementing the same idea directly, based on the descriptions I've provided.
精彩评论