我最近为F#项目编写了以下组合和排列函数,但我很清楚它们远未优化.
/// Rotates a list by one place forward.
let rotate lst =
List.tail lst @ [List.head lst]
/// Gets all rotations of a list.
let getRotations lst =
let rec getAll lst i = if i = 0 then [] else lst :: (getAll (rotate lst) (i - 1))
getAll lst (List.length lst)
/// Gets all permutations (without repetition) of specified length from a list.
let rec getPerms n lst =
match n, lst with
| 0, _ -> …Run Code Online (Sandbox Code Playgroud) 我需要在给定列表上生成排列.我设法做到这一点
let rec Permute (final, arr) =
if List.length arr > 0 then
for x in arr do
let n_final = final @ [x]
let rest = arr |> List.filter (fun a -> not (x = a))
Permute (n_final, rest)
else
printfn "%A" final
let DoPermute lst =
Permute ([], lst)
DoPermute lst
Run Code Online (Sandbox Code Playgroud)
这段代码存在明显的问题.例如,列表元素必须是唯一的.而且,这与我在任何其他语言中生成直接实现时使用的方法相同.有没有更好的方法在F#中实现它.
谢谢!