Created
February 11, 2009 06:22
-
-
Save mattpodwysocki/61874 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#light | |
namespace CodeBetter.Extensions | |
[<CompilationRepresentation(CompilationRepresentationFlags.ModuleSuffix)>] | |
[<CompilationMapping(SourceConstructFlags.Module)>] | |
module List = | |
// Insert | |
// The non-overloaded version of 'insert' | |
let rec insertBy (cmp:'a -> 'a -> int) (x:'a) : 'a list -> 'a list = function | |
| [] -> [x] | |
| y::ys' as ys -> | |
if cmp x y = 1 then y :: insertBy cmp x ys' | |
else x :: ys | |
// insert :: Ord a => a -> [a] -> [a] | |
let insert e ls = insertBy compare e ls | |
// Lines | |
let rec break (p:'a -> bool) : 'a list -> 'a list * 'a list = function | |
| ([] as xs) -> (xs, xs) | |
| (x::xs' as xs) -> | |
if p x then ([], xs) | |
else | |
let (ys,zs) = break p xs' | |
(x::ys, zs) | |
// Sort | |
let defaultSort (l:'a list) = | |
l |> List.sort compare | |
// Group functions | |
let rec span (p:'a -> bool) : 'a list -> 'a list * 'a list = function | |
| [] -> [], [] | |
| (x::xs' as xs) -> | |
let ys, zs = span p xs' | |
if p x then x::ys, zs else [], xs | |
let rec groupBy (eq:'a -> 'a -> bool) : 'a list -> 'a list list = function | |
| [] -> [] | |
| x::xs -> | |
let ys, zs = span (eq x) xs | |
(x::ys) :: groupBy eq zs | |
let group (l:'a list) = groupBy (=) l | |
// Take/Drop | |
let rec take (n:int) : 'a list -> 'a list = function | |
| _ when n <= 0 -> [] | |
| [] -> [] | |
| x::xs -> x :: take (n - 1) xs | |
let rec drop (n:int) : 'a list -> 'a list = function | |
| xs when n <= 0 -> xs | |
| [] -> [] | |
| (_::xs) -> drop (n-1) xs | |
let splitAt (n:int) (xs:'a list) : 'a list * 'a list = | |
(take n xs, drop n xs) | |
let rec dropWhile (p:'a -> bool) : 'a list -> 'a list = function | |
| [] -> [] | |
| (x::xs' as xs) -> | |
if p x then dropWhile p xs' else xs | |
let rec takeWhile (p:'a -> bool) : 'a list -> 'a list = function | |
| [] -> [] | |
| x::xs -> if p x then takeWhile p xs else [] | |
// Delete functions | |
let rec deleteBy (eq:'a -> 'a -> bool) (x:'a) : 'a list -> 'a list = function | |
| [] -> [] | |
| y::ys -> if (eq x y) then ys else y :: deleteBy eq x ys | |
let delete x xs = deleteBy (=) x xs | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment