简体   繁体   English

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

[英]F# selection sort on list of random integers

I am new to F# and trying to figure out some basics but am stumbling along slowly.我是 F# 的新手,并试图弄清楚一些基础知识,但进展缓慢。 In the code below I am trying to generate a list of random integers and then sorting it.在下面的代码中,我试图生成一个随机整数列表,然后对其进行排序。

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

So two things...one is the error I'm getting:所以有两件事......一个是我得到的错误:

stdin(515,19): error FS0001: This expression was expected to have type
    'a list    
but here has type
    'a list -> 'a list

The other is with the random number list.另一个是随机数列表。 It works, but I want the numbers generated to be less than 100, instead of the massive values I'm getting now.它有效,但我希望生成的数字小于 100,而不是我现在得到的大量值。

Thanks for your patience and help!感谢您的耐心和帮助!

As mentioned in the comment, there is no need for l in let rec selectionSort .正如评论中提到的,在let rec selectionSort中不需要l Fixed code:固定代码:

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

Explanation:解释:

let vname = function
   | ... -> ...
   | ... -> ...

is the short form of是的缩写形式

let vname arg = match arg with
   | ... -> ...
   | ... -> ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM