List.sortBy

Takes a function that converts the elements in the given list into some other value and then the natural sorting order is used on the return value.

Example

> [ "1"; "2"; "3"; "10"; "20"; "30"; "101" ] |> List.sort

val it : string list = ["1"; "10"; "101"; "2"; "20"; "3"; "30"]

this is not the order we probably want so:

> [ "1"; "2"; "3"; "10"; "20"; "30"; "101" ] |> List.sortBy (fun s -> System.Int32.Parse s)

val it : string list = ["1"; "2"; "3"; "10"; "20"; "30"; "101"]

this allows use to convert the strings of the orginal list into integers for sorting but get back the orginal string values in the resulting sorted list.

List.sortWith

On the other hand we might want to perform a reverse sort and for this we provide a method that does the comparison

> [ "bob"; "ann"; "gary"; "florence"; "bart" ] |> List.sortWith (fun a b -> -a.CompareTo(b))

val it : string list = ["gary"; "florence"; "bob"; "bart"; "ann"]

you'll see here that we used the CompareTo method of System.String and then used the negative value of what was returned.

List.permute

Finally List.permute is used to create a new list where the function argument provides a mapping from the original index to the new index position

> [0 .. 9] |> List.permute (fun i ->

match i with

| 0 -> 1

| 1 -> 2

| 2 -> 3

| 3 -> 4

| 4 -> 5

| 5 -> 6

| 6 -> 7

| 7 -> 8

| 8 -> 9

| 9 -> 0

| _ -> i);;

val it : int list = [9; 0; 1; 2; 3; 4; 5; 6; 7; 8]

remember if your indexMapping function misses any index number (ie if 0 is never appears as a result of the function) then you will get an exception indicating that

"the function did not compute a permutation"

> [0 .. 9] |> List.permute (fun i ->

match i with

| 0 -> 1

| 1 -> 2

| 2 -> 3

| 3 -> 4

| 4 -> 5

| 5 -> 6

| 6 -> 7

| 7 -> 8

| 8 -> 9

//| 9 -> 0 Oops we forgot to map to the 0 index

| _ -> i);;

System.ArgumentException: the function did not compute a permutation

Parameter name: indexMap

at Microsoft.FSharp.Primitives.Basics.Array.permute[a](FastFunc`2 indexMap, a[] arr)

at Microsoft.FSharp.Collections.ListModule.permute[T](FastFunc`2 indexMap, FSharpList`1 list)

at <StartupCode$FSI_0013>.$FSI_0013.main@()

By on 5/21/2009 2:46 PM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper