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: 
11: 
12: 
13: 
let a = ["ccc";"aaaz";"d";"bb"]
let b = ["Cameron",31; "Rachel",29; "Nicole",10; "Katheryn",8; "Charlotte",1]

let sorted lst key = 
    List.map(fun v -> key v, v) lst
    |> List.sortBy(fun (sv,v) -> sv)
    |> List.map(fun (sv,v) -> v)

(* Sorting the list a by the length 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 : lst:'a list -> key:('a -> 'b) -> 'a list (requires comparison)

Full name: Script.sorted
val lst : 'a list
val key : ('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 map : mapping:('T -> 'U) -> list:'T list -> 'U list

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

Full name: Microsoft.FSharp.Collections.List.sortBy
val sv : 'b (requires comparison)
val s : string
property System.String.Length: int
val name : string
val age : int
Next Version Raw view Test code New version

More information

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