开发者

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. 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.

Thanks for your patience and help!


As mentioned in the comment, there is no need for l in let rec selectionSort. 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
   | ... -> ...
   | ... -> ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜