- 论坛徽章:
- 95
|
原帖由 win_hate 于 2008-11-17 20:05 发表
把你的 Haskell 代码贴出来给我学习一下吧,
这是我把你的 ML 代码翻译为 Haskell 后的结果,你可以参考下:
- module Permutation (nextPerm, nthPerm, allPerm) where
- import Data.List (genericTake, genericIndex, sort)
- nextPerm :: Ord a => [a] -> [a]
- nextPerm (x:xs) = next [x] xs
- where
- next rs [] = rs
- next (r:rs) (y:ys) = if r <= y then next (y:r:rs) ys else swap (r:rs)
- where
- swap [x] = y:x:ys
- swap (x1:x2:xs) = if y < x2 then x1 : swap (x2:xs) else (y:x2:xs) ++ (x1:ys)
- nthPerm :: Ord a => Integer -> [a] -> [a]
- nthPerm n xs = (iterate nextPerm xs) `genericIndex` n
- allPerm :: Ord a => [a] -> [[a]]
- allPerm xs = genericTake (factorial n) $ iterate nextPerm xs'
- where
- n = length xs
- factorial n = product [1..n]
- xs' = sort xs
复制代码 |
|