gpt4 book ai didi

list - F#选择对随机整数列表进行排序

转载 作者:行者123 更新时间:2023-12-02 04:09:10 26 4
gpt4 key购买 nike

我是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,而不是我现在得到的庞大值。

感谢您的耐心配合和帮助!

最佳答案

如评论中所述,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
| ... -> ...
| ... -> ...

关于list - F#选择对随机整数列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6106693/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com