我是F#的新手,并试图弄清楚一些基本知识,但我慢慢地磕磕绊绊。在下面的代码中,我试图生成一个随机整数列表,然后对其进行排序。
let randomNumberList count =
let r = System.Random()
List.init count (fun _ -> r.Next(100))
let rec selectionSort l = function
| [] -> []
| l -> let min = List.min l in
let rest = List.filter (fun i -> i <> min) l in
let sortedList = selectionSort rest in
min :: sortedList
sortedList = selectionSort l
let unsortedList = randomNumberList 10
printfn "%A" unsortedList
printfn "%A" sortedList
所以有两件事......一件是我得到的错误:
stdin(515,19): error FS0001: This expression was expected to have type
'a list
but here has type
'a list -> 'a list
另一个是随机数列表。它有效,但我希望生成的数字小于100,而不是我现在得到的大量值。
感谢您的耐心和帮助!
答案 0 :(得分:1)
正如评论中所述,l
中不需要let rec selectionSort
。固定代码:
let randomNumberList count =
let r = System.Random()
List.init count (fun _ -> r.Next(100))
let rec selectionSort = function
| [] -> []
| l -> let min = List.min l in
let rest = List.filter (fun i -> i <> min) l in
let sortedList = selectionSort rest in
min :: sortedList
let unsortedList = randomNumberList 10
let sortedList = selectionSort unsortedList
printfn "%A" unsortedList
printfn "%A" sortedList
System.Console.ReadLine() |> ignore
说明:
let vname = function
| ... -> ...
| ... -> ...
是
的缩写形式let vname arg = match arg with
| ... -> ...
| ... -> ...