Skip to content

Instantly share code, notes, and snippets.

@imerchant
Last active May 17, 2016 22:01
Show Gist options
  • Save imerchant/bbd46c8c225a0de0af3ba6a615619149 to your computer and use it in GitHub Desktop.
Save imerchant/bbd46c8c225a0de0af3ba6a615619149 to your computer and use it in GitHub Desktop.
open System
type Message =
| Default
| Custom of string
type Person = {
name : string
age : int
}
let person name age = {name = name; age = age }
let imran = person "Imran" 1
let mo = person "Mo" 2
let david = person "David" 3
let byAge person = person.age
let ascending item1 item2 = item1 <= item2
let people = [| imran; mo; david |]
let private sortChecker previousVal thisItem selector comparator message =
let thisVal = selector thisItem
let compare = comparator previousVal thisVal
if compare = false then
match message with
| Default -> sprintf "collection is not sorted (item1: %O, item2: %O)" previousVal thisVal
| Custom(x) -> x
|> failwith
thisVal
let shouldBeSorted (selector : 'TItem -> 'TProp) (comparator : 'TProp -> 'TProp -> bool) message (collection : 'TItem[]) =
collection
|> Array.fold (fun previous item -> sortChecker previous item selector comparator message) (selector collection.[0])
|> ignore
people |> shouldBeSorted byAge ascending Message.Default
people |> shouldBeSorted (fun p -> p.age) (fun age1 age2 -> age1 <= age2) (Message.Custom "omg why")
// let rec whatever accum (selector : 'TItem -> 'TProp) (comparator : 'TProp -> 'TProp -> bool) (collection : List<'TItem'>) =
// let prop = selector collection.Head
// let compare = comparator accum prop
// if compare = false then failwith <| sprintf "collection is not sorted (item1: %O, item2: %O)" accum prop
// whatever prop selector comparator collection.Tail
// let shouldBeSorted' (selector : 'TItem -> 'TProp) (comparator : 'TProp -> 'TProp -> bool) (collection : List<'TItem'>) =
// whatever collection.Tail selector comparator collection.Head
// people |> shouldBeSorted' (fun p -> p.age) (fun age1 age2 -> age1 <= age2)
// let ints = [| 1; 2; 3 |]
// ints |> shouldBeSorted (fun i -> i) (fun item1 item2 -> item1 <= item2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment