2 people like it.

Python's sorted function

This is an attempt to produce similar behavior as seen in the sorted( ) function in Python. Supporting only one of the three optional arguments. The key - Specifies a function of one argument that is used to extract a comparison key from each list element

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
let a = ["ccc";"aaaz";"d";"bb"]
let b = ["Cameron",31; "Rachel",29; "Nicole",10; "Katheryn",8; "Charlotte",1]

let sorted a b = List.sortBy b a

(* Sorting the list a by the last character of each string in the list *)
sorted a (fun s -> s.[s.Length - 1])

(* Sorting the list b by the age of each tuple in the list *)
sorted b (fun (name,age) -> age)
val a : string list

Full name: Script.a
val b : (string * int) list

Full name: Script.b
val sorted : a:'a list -> b:('a -> 'b) -> 'a list (requires comparison)

Full name: Script.sorted
val a : 'a list
val b : ('a -> 'b) (requires comparison)
Multiple items
module List

from Microsoft.FSharp.Collections

--------------------
type List<'T> =
  | ( [] )
  | ( :: ) of Head: 'T * Tail: 'T list
  interface IEnumerable
  interface IEnumerable<'T>
  member Head : 'T
  member IsEmpty : bool
  member Item : index:int -> 'T with get
  member Length : int
  member Tail : 'T list
  static member Cons : head:'T * tail:'T list -> 'T list
  static member Empty : 'T list

Full name: Microsoft.FSharp.Collections.List<_>
val sortBy : projection:('T -> 'Key) -> list:'T list -> 'T list (requires comparison)

Full name: Microsoft.FSharp.Collections.List.sortBy
val s : string
property System.String.Length: int
val name : string
val age : int

More information

Link:http://fssnip.net/4C
Posted:6 years ago
Author:Cameron Frederick
Tags: sorting , sorted , list