好吧,我已经花了将近10个小时试图在F#中解决这个问题。
我需要按字母顺序对列表进行排序并反转列表
我想出了什么:
[<EntryPoint>]
printfn "Enter 10 Names";;
let mutable list = [for i in 1 .. 10 -> System.Console.ReadLine(); ]
printfn "%A" list
//let list = List.sort
//printfn "%A" list
let reverseList list = List.fold (fun acc elem -> elem::acc) [] list
printfn "%A" (reverseList [for i in 1 .. 10 -> List.iteri])
答案 0 :(得分:5)
[<EntryPoint>]
printfn "Enter 10 Names";;
let list = [for i in 1 .. 10 -> System.Console.ReadLine(); ]
printfn "%A" list
// List.sort takes 'list' as a parameter and returns sorted list
//(in the case of string list - alphabetically)
let sortedlist = List.sort list
printfn "%A" sortedlist
// List.rev takes 'sortedlist' as a parameter and returns reversed list
let sortedreversedlist = List.rev sortedlist
printfn "%A" sortedreversedlist
或者您可以将List.sort函数的结果作为参数传递给List.rev函数,而不将其赋值给变量:
let sortedreversedlist' = List.rev (List.sort list)
printfn "%A" sortedreversedlist'
F#也有管道运营商'|&gt;'可用于在列表上创建“管道”操作(将上一个函数的结果重定向到下一个)。它允许以不同的方式编写相同的函数序列(按它们将执行的顺序):
let sortedreversedlist'' = list |> List.sort |> List.rev
printfn "%A" sortedreversedlist''
答案 1 :(得分:0)
let reverseComparer expr =
match expr with
| true -> -1
| false -> 1
| _ -> 0
let reversedNames = names |> List.sortWith (fun previous follower -> reverseComparer (previous > follower))
答案 2 :(得分:0)
let list = [ "bbc"; "CNN"; "cnn"; "abc"; "1"; "ABC"; "BBC"; "2"]
let sortedList = Set.toList( Set.ofList list )
let reversedList = List.rev sortedList;;