我试图从头开始这样做,而不使用标准库之外的库.继承我的代码:
permutations :: [a] -> [[a]]
permutations (x:xs) = [x] : permutations' xs
where permutations' (x:xs) = (:) <$> [x] <*> split xs
split l = [[x] | x <- l]
Run Code Online (Sandbox Code Playgroud)
问题是这只产生一个非确定性计算的分支.理想情况下我想要
(:) <$> [x] <*> ((:) <$> [x] <*> ((:) <$> [x] <*> ((:) <$> [x] <*> xs)))
Run Code Online (Sandbox Code Playgroud)
但我找不到干净利落的方法.我想要的结果是这样的:
permutations "abc" -> ["abc", "acb", "bac", "bca", "cab", "cba"]
Run Code Online (Sandbox Code Playgroud)
我该怎么做呢?
haskell ×1